So I have a first and last variable which is the starting and ending markers that I want to get rid of. So the starting input for example would be
[5, 10, 15, 20, 25]
And say first = 1
and last = 3
. The would mean that the elements 10, 15, and 20 would not be included in the new array since they are at the indexes between 1-3, inclusive, so that new array without those nums would be the output. Here’s what I have so far:
int [] newArr = new int[arr.length - (last - first) - 1]; for (int i = 0; i < newArr.length; i++) { if (i < first || i > last) { newArr[i] = arr[i]; } }
They’re just changing to 0’s, and for some reason I can’t think of what to do next.
Advertisement
Answer
The simplest approach is probably just to keep track of a separate index for where you are inserting elements into the new array.
int [] newArr = new int[arr.length - (last - first) - 1]; for (int i = 0, j = 0; i < arr.length; i++) { if (i < first || i > last) { newArr[j++] = arr[i]; } }