Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group "unlike" elements when iterating array (e.g.:{1,2,2,1,3,3,3,2,1,1} to {1,2}{2,1,3}{3}{3,2,1}{1})?

I have array

int a[]={1,2,2,1,3,3,3,2,1,1};

If I want to group the same elements when iterating them (without any temp variables or arrays to store or copy elements), for example, print same elements in a line when iterating:

1 
2 2 
1 
3 3 3 
2 
1 1 

I can have for loops and if conditions like this:

#include <stdio.h>
int main(){
    int a[]={1,2,2,1,3,3,3,2,1,1};
    for(int i=0,j=0;i<sizeof(a)/sizeof(int);i++){
        if(i==sizeof(a)/sizeof(int)-1 || a[i]!=a[i+1]){
            for(;j<=i;j++){
                printf("%d ",a[j]);
            }
            printf("\n");
        }
    }
    return 0;
}

But now I want to group "unlike" elements when iterating : each group does not have same elements nearby:

1 2 
2 1 3 
3 
3 2 1 
1 

is it possible to have solution that is similar to previous version

for(int i=0,j=0;i<sizeof(a)/sizeof(int);i++){
    if(...){
        for(;j<=i;j++){
            printf("%d ",a[j]);
        }
        printf("\n");
    }
}

that can iterate the array to print the result like that without any temp variables?

like image 857
ggrr Avatar asked Dec 06 '25 07:12

ggrr


1 Answers

int a[] = {1,2,2,1,3,3,3,2,1,1};

int prev = a[0];
bool first = false;
printf("%d", prev);

for (int i=1; i < sizeof(a) / sizeof(int); ++i) {
    int curr = a[i];
    if (curr != prev) {
        // start a new line for a new group
        printf("\n");
        first = true;
    }
    if (!first) {
        // print a space after each element
        printf(" ");
    }
    printf("%d", curr);
    first = false;
    prev = curr;
}
like image 61
Tim Biegeleisen Avatar answered Dec 08 '25 21:12

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!