Home > Blockchain >  Delete duplicats in a double[] array
Delete duplicats in a double[] array

Time:03-03

I want to delete duplicates in a double[] array. Unfortunately, I cannot use an ArrayList or whatsoever, it has to be a "normal" double array. I tried to use the binarySearch() method of the class Array, but could not find a good solution to it, because I must not only search for but also delete the duplicates. Then I would have to reduce the length every time I delete such a duplicate.

Is there any solution for this problem?

CodePudding user response:

public static double[] removeDuplicates(double[] arr) {
    return Arrays.stream(arr).distinct().toArray();
}

CodePudding user response:

double[] arr = {...};

double[] removed = new double[arr.length];

for (int k=0; k<removed.length; k  ) {
  boolean b = false;

  for (int i=0; i<arr.length; i  ) {
    b = false;

    for (int j=0; j<removed.length; j  ) {

      if (arr[i] == arr[j] && i != j) b = true;
    }

    if (!b) removed[k] = arr[i];

  }

}

// Then parse through 'removed' to make a smaller list of all initialized elements.
  • Related