Skip to content
Advertisement

How can I count subsequently equal values in an int array

I would like to count subsequently equal values in an int array and return an array with the count and another array with the value order.

E.g. i would like to transform:

int arr = {0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,0,0,0,1,1,1,2,2,2,2,0,0,0,0};

To:

int arr = {11,5,4,3,3,4,4}; // The count
int idx = {0,1,2,0,1,2,0}; // The order

Can you help me achieve this?

Advertisement

Answer

This should do the job:

int[] arr = {0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,0,0,0,1,1,1,2,2,2,2,0,0,0,0};
//First determine how many subsequently equal values there are
int countEquals = 1;
for (int i = 1; i < arr.length; i++) {
    if (arr[i] != arr[i-1]) {
        countEquals++;
    }
}
//Then calculate the order and count
int[] count = new int[countEquals];
int[] order = new int[countEquals];
int index = 0;
Arrays.fill(count, 1);
for (int i = 1; i < arr.length; i++) {
    if (arr[i] == arr[i-1]) {
        count[index]++;
    } else {
        order[index] = arr[i-1];
        index++;
    }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement