I want to match all the elements of the same array with each other, but an element cannot be matched with itself.
The code I got is the following:
function combine(list) {
var pairs = new Array((list.length * (list.length - 1)) / 2),
pos = 0;
for (var i = 0; i < list.length; i++) {
for (var j = i + 1; j < list.length; j++) {
pairs[pos++] = [list[i], list[j]];
}
}
return pairs;
}
var result = combine([1, 2, 3, 4]);
console.log("Combinaciones = "+ JSON.stringify(result));
The result I expect as a solution will be:
Combinaciones = [[1,2],[1,3],[1,4],[2,1],[2,3],[2,4],[3,1],[3,2],[3,4],[4,1],[4,2],[4,3]]
However I get this and I don't know where the error is:
Combinaciones = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]];
So for example if it checks 1.2 I also want it to check 2.1 but not each number with itself.
How to obtain the combinations of possible pairs in both senses, only omitting the one of a number with itself?
The variable j in the second loop would have to be initialized to 0 , otherwise it would take the value two when the first loop was in the first iteration. It would look like this: