Search code examples
algorithmloopscombinations

"For" loop for all possible combinations without repetition


I have a table of values, and I need to compare all of them. The problem is, I don't want to compare the same values two times (for example, loop compares values 1 - 2, 1 - 3, 2 - 1, and 2 - 1 is the same as 1 - 2). I wrote a loop inside a loop that looks like this:

for (int i = 0; i < numberOfSets; i++) {
        for (int j = 1; j < numberOfSets; j++) {

        //compare element i and j here
    }
}

But how can I modify this loop to skip repetitions? What I tried so far was incrasing j when i == j:

for (int i = 0; i < numberOfSets; i++) {
        for (int j = 1; j < numberOfSets; j++) {


            if(i == j) {
                j++;
            } else {
                //compare element i and j
            }
    }
}

But it doesn't seem to work correctly. Is there a better way to loop the way I want to?


Solution

  • Simply start the inner loop with j = i + 1.

    for (int i = 0; i < numberOfSets; i++) {
        for (int j = i + 1; j < numberOfSets; j++) {
            // do stuff
        }
    }