Search code examples
javacomputer-science

Nested for loop to compare pairs


My java project is having a little issue here, I simplified it to the following codes. My codes print out:

Index 0 and 1 are pointing to same value. Index 1 and 0 are pointing to same value. Index 3 and 4 are pointing to same value. Index 4 and 3 are pointing to same value.

But what I want is:

Index 0 and 1 are pointing to same value. Index 3 and 4 are pointing to same value.

Because 0 and 1, 1 and 0 are really same pairs, any suggestion?

int[] arr={4,4,5,6,6,};
    
    for(int n=0; n<arr.length; n++)
    {
        for(int m=0; m<arr.length; m++)
        {
            if(arr[n]==arr[m] && n!=m)
            {
                System.out.println("Index "+n+" and "+m+" are pointing to same value.");
            }
        }
    }

Solution

  • If you want to filter out the duplicate ones, change for(int m=0; m<arr.length; m++) to for(int m=n+1; m<arr.length; m++)