I want to count the number of consecutive repeating numbers from a list of bytes and show them as two integers arrays:
- The first array contains the non-repeating integer values.
- The second array contains the consequent repetition counts.
So, for an input like this:
Byte[] bytes = new Byte[] {2, 2, 2, 0, 0, 0, 0, 2, 2, 0, 0, 2};
I expect an output like this:
integers -[2, 0, 2, 0, 2]
frequency -[3, 4, 2, 2, 1]
Which is basically a compressed view of the input. The output says integer 2 repeats 3 times followed by 0 that repeats 4 times followed by 2 that repeats 2 times and so on..
I have written the below code.
List<Byte> integers = new ArrayList<>();
List<Integer> frequencies = new ArrayList<>();
for (int i=0; i < bytes.size() - 1; i++) {
Byte current = bytes.get(i);
Byte next = bytes.get(i+1);
if (current == next) {
count ++;
// if all bytes are of the same type
if (count == bytes.size() || i == bytes.size() - 2) {
integers.add(current);
frequencies.add(count);
}
continue;
integers.add(current);
frequencies.add(count);
count = 1;
}
}
System.out.println("integers " + integers + " - frequency " + frequencies);
This code works for most cases. But I am missing some edge cases. Like for the example input, the output is missing to reach to the last element 2. The output from my code for input is -
integers -[2, 0, 2, 0]
frequency -[3, 4, 2, 2]
I am adding a bunch of if
statements to cover all corner cases but I want to know if there is a cleaner solution to this?
I didn't try running this code on an IDE but I think this should suffice:
int count = 1;
int index = 0;
byte current = bytes[index];
while (index < bytes.length - 1) {
index++;
if (bytes[index] == current) {
count++;
} else {
integers.add(current);
frequencies.add(count);
count = 1;
current = bytes[index];
}
}
integers.add(current);
frequencies.add(count);