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.

有帮助吗?

解决方案

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;
}

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top