Combinations / possible pairs in the same array

1

I want to pair all the elements of the same array together, but one element can not be paired 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 that I hope will be the solution:

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 do not know where the error is:

Combinaciones = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]];

So that for example if you check the 1.2 I also want you to check the 2.1 but not each number with itself.

How to get combinations of possible pairs in both directions, just by omitting a number with yourself?

    
asked by Norak 13.11.2017 в 12:31
source

1 answer

3

The variable j in the second loop would have to initialize it to 0, because otherwise it would take the value two when the first loop was in the first iteration. It would look like this:

for (var i = 0; i < list.length; i++) {

        for (var j = 0; j < list.length; j++) {

            pairs[pos++] = [list[i], list[j]];

        }

    }
    
answered by 13.11.2017 / 12:41
source