solving something in algoexpert and getting weird index out of bound exception:
the question is simply to take an array and another int and put all the numbers that equal to this int in the end of the array, like this:
array: [2, 1, 2, 2, 2, 3, 4, 2] integer toMove: 2
output: [1,3,4,2,2,2,2,2]
so I wrote this algorithm:
class Program {
public static List<Integer> moveElementToEnd(List<Integer> array, int toMove) {
// Write your code here.
int newArr[] = new int[array.size()];
int lastIndertedNotToMoveIdx = 0;
int endOfArrayIdx = array.size();
// ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i <= array.size(); i++) {
if (array.get(i) == toMove) {
newArr[endOfArrayIdx] = array.get(i);
endOfArrayIdx = endOfArrayIdx-1;
} else {
newArr[lastIndertedNotToMoveIdx] = array.get(i);
lastIndertedNotToMoveIdx++;
}
}
List<Integer> ret_list = new ArrayList<Integer>();
for(Integer num:newArr) {
ret_list.add(num);
}
return ret_list;
}
}
but here newArr[endOfArrayIdx] = array.get(i); I get this message:
java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8
at Program.moveElementToEnd(Program.java:12)
at AeJsonTest.getActual(AeJsonTest.java:27)
at Main.main(Main.java:57)
not sure why...
0 .. size-1are possible. SoendOfArrayIdxshould bearray.size()-1.to take an array, implementing a function taking aList<>parameter looks a detour.)