I'm trying to split an array into subarrays by value. For example (with the main function delaration and class name removed):
int[] arr = {1, 5, 3, 4, 2, 2, 5, 3, 1};
for (int i : splitByVal(arr)) {
System.out.println(i);
}
I already have one way to do this:
public int[][] splitByVal(arr) {
int prevItem = arr[0];
ArrayList<Integer[]> chunks = new ArrayList<Integer[]>();
ArrayList<Integer> currentChunk = new ArrayList<Integer>();
for (int i : arr) {
if (i == prevItem) {
currentChunk.add(i);
}
else {
chunks.add((Integer[]) currentChunk.toArray());
currentChunk.clear();
}
prevItem = i;
}
return chunks.toArray()
}
What I want to know is: Is there a better way to do this?
slope? if current element is not the same asprevItemthenprevItem = i;. and you should put.add(i)outside ofif-elseblockslopeis supposed to bei.