0

I have an array like this:
double[] my_input_array = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
and some known positions which represent where to remove items from the array.
For example if positions are 3 and 7 I would like to get a my_output_array = { 0, 1, 2, 4, 5, 6, 8 };

So I would like to have a function like this:

public double[] getShinkedArray(double[] my_input_array, int... positions){
    /* SOME CODE */
    return my_output_array;
}

I noticed this question Delete item from array and shrink array but these answers remove only one element at time from an array.

Community
  • 1
  • 1
madx
  • 6,723
  • 4
  • 55
  • 59
  • Removing multiple elements is basically the same except you do it multiple times or check an array of positions. What is the problem you are having? – Peter Lawrey Jan 26 '14 at 15:40

2 Answers2

2

You can't shrink an array, you need to create a new one with the new size. You could do something like:

public double[] getShinkedArray(final double[] my_input_array, final int... positions) {
    double[] outputArray = new double[my_input_array.length - positions.length];
    for (int i = 0, j = 0; i < my_input_array.length; i++) {
        if (Arrays.binarySearch(positions, i) < 0) {
            outputArray[j++] = my_input_array[i];
        }
    }
    return outputArray;
}
Keppil
  • 45,603
  • 8
  • 97
  • 119
0

Create a new array, loop through the old one, for each step of the loop check if the loop index is present in positions. If it is, go to the next iteration of the loop. If it isn't, add the element at that index in the old array to the new array. Return the new array.

Mike B
  • 5,390
  • 2
  • 23
  • 45