I'm trying to write a function that returns an array of unique numbers. The array must be sorted. The function works fine when there are more than just one element, but it doesn't work for when there is just one element in the array. The function should return the only element found in that array, but instead, it is returning an empty array.
Why is this happening?
Array must be sorted for numUnique and removeDuplicates
public static int numUnique (double[] list){
int uniques = 1;
int i = 1;
if(list.length == 0) return 0;
while(i<list.length){
if(list[i] != list[i - 1])
uniques++;
i++;
}
return uniques;
}
public static double[] removeDuplicates(double[] list){
double[] arrayOfUniques = new double[numUnique(list)];
if(list.length == 0) return arrayOfUniques;
int uniques = 1;
int i = 1;
arrayOfUniques[0] = list[0];
while(i < list.length){
if(list[i] != list[i - 1])
arrayOfUniques[uniques++] = list[i];
i++;
}
return arrayOfUniques;
}
Array:
double[] a = {11,11,21,31,41,41,51,61,61,61,71,71,81,91,91,100,100};
Output:
Unique numbers: 9
Array of uniques: [11.0, 21.0, 31.0, 41.0, 51.0, 61.0, 71.0, 81.0, 91.0]
But it doesn't work when the array just has one element:
double[] a = {11};
Output:
Unique numbers: 0
Array of uniques:[]