So I'm trying to make a program that counts the occurences of int in an array. what i tried to do is to make a method that lists the unique integers, then another method to compare the list items to the original array items.
public List listUnique(int[] arr){
Arrays.sort(arr);
List <Integer> temp = new ArrayList<>();
int currentInt = 0;
for (int i = 0; i < arr.length; i++){
if(arr[i] != currentInt){
temp.add(arr[i]);
currentInt = arr[i];
}
}
return temp;
}
public int[] countDupli(List unique, int[] arr){
int [] ret = new int[unique.size()];
Iterator <Integer> iterator = unique.iterator();
for (int l = 0; l < unique.size(); l++){
ret[l] = iterator.next().intValue();
}
int[] dupli = new int[ret.length];
for (int j = 0; j < ret.length; j++){
dupli[j] = 0;
}
for (int k = 0; k < ret.length; k++){
for (int i = 0; i < arr.length; i++){
if ( ret[k] == arr[i]){
dupli[k]+= 1;
}
}
k++;
}
return dupli;
}
It isn't doing what is intended to do tho. For example, an input of {1,2,...,1,2} 10 items of those, prints the correct unique items but only outputs the count of 1 but not 2. dupli = [5,0]. where did the algorithm go wrong? thanks