My goal is to be able to count groups of the same integer within an array. For example, in an array like so, {1, 1, 1, 2, 2, 3, 1, 1}
, there are 4 groups:
- of at least size 1: 3 groups
- of at least size 2: 1 group
- of at least size 3
I'm having issues accomplishing this without sorting the array. When it gets sorted I lose count of the group of two 1's at the end of the array, since it gets put next to the other groups of 1's.
int result = (int) Stream.of(1, 1, 1, 2, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 4, 4, 4, 6)
.collect(Collectors.groupingBy(i -> i))
.entrySet().stream()
.filter(entry -> entry.getValue().size() >= 1) // specify the size
.count()
return result;
This expected output for each size is as follows:
size 1 count == 8
size 2 count == 5
size 6 count == 1
size 8 count == 1
The actual output is as follows:
size 1 count == 6
size 2 count == 3
size 6 count == 2
size 8 count == 1
The difference is a result of the array being sorted prior to the count taking place. Is there any way to accomplish this?
Edit: A group is essentially any place where the same integer repeats, until an integer of a different value, is ahead of it; so, the groups of size 2 in this in this code are any at index 0 to 2(inclusive), index 4 - 5(inclusive), index 6 - 15(inclusive, index 16 - 18(inclusive, and index 20 -22(inclusive). Since there are 5 groups that are of at least size 2 a count of 5 should be returned.
An imperative style of code for my goal.
Scanner key = new Scanner("1 1 1 2 1 1 3 3 3 3 3 3 3 3 3 3 4 4 4 5 4 4 4 6");
int cnt = 0;
int counter = 0;
int i = 0;
while(key.hasNextInt()) {
int next = key.nextInt();
if(next == array[i]) {
counter++;
}
if(i + 1 < array.length && i -1 >= 0
&& counter >=size
&& next != array[i + 1]
&& next == array[i-size + 1]) {
cnt++;
counter = 0;
}
i++;
}
return cnt;
The expected return for this is the same as above.
The actual return is:
size 1 count == 7
size 2 count == 5
size 6 count == 3
size 8 count == 1
The problem with this loop is I believe it is skipping first piece and the end piece of the array.
I'm not having the same sorting issue as the Stream way.
Ideally, this wouldn't require any external utilities/libraries.