ElSajko ElSajko - 2 months ago 8
Javascript Question

Two nested for/loops without duplicated pairs

We have array:

var arr = [0,1,2];


and loops:

for ( var i=0; i<arr.length; i++ ) {
for ( var j=0; j<arr.length; j++ ) {
if ( arr[i] == arr[j] ) continue;
console.log(arr[i], arr[j]);
}
}


and output:

0,1 //a--|
0,2 //b--|--|
1,0 //a--| |
1,2 //c-----|--|
2,0 //b-----| |
2,1 //c--------|


as we can see there are duplicated pairs (in comments a, b and c occurs twice)

the only way we can get rid of duplicated pairs is to store already "matched" pairs in some sort of memory?

var mem = {};

for ( var i=0; i<arr.length; i++ ) {
for ( var j=0; j<arr.length; j++ ) {
var left = i;
var right = j;
if ( left > right ) {
var temp = right;
right = left;
left = temp;
}

if ( arr[i] == arr[j] || mem[arr[left]+","+arr[right]] ) continue;

console.log(arr[i], arr[j]);
mem[arr[left]+","+arr[right]] = true;
}
}


and output:

0,1
0,2
1,2


but this takes additional memory (for bigger arrays it takes a lot of it..)

is there any other way without storing anything additional?

Answer

If your input array is unique why don't you just start your j from i+1

for ( var i=0; i<arr.length; i++ ) {
    for ( var j= i + 1 ; j<arr.length; j++ ) {
        console.log(arr[i], arr[j]);
    }
}
Comments