2
let input = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

and i want output should be:

output = {
    first: [[1,2], [3,4], [5,6], [7,8], [9,10]],
    second: [[1,3], [2,4], [5,7], [6,9], [8,10]],
    third: [[1,4], [2,3], [5,8], [7,9], [6,10]],
    fourth: [[1,5], [2,6], [3,7], [8,9], [4,10]],
    fifth: [[1,6], [2,8], [3,5], [4,9], [7,10]],
    sixth: [[1,7], [2,9], [3,6], [4,8], [5,10]],
    seventh: [[1,8], [2,7], [4,6], [5,9], [3,10]],
    eighth: [[1,9], [3,8], [4,5], [6,7], [2,10]],
    ninth: [[1,10], [2,5], [3,9], [4,7], [6,8]],
}

I need to write a code in javascript / typescript / nodejs by which i can put number ranges and will get a combinations of given numbers**( n-1 ), i want a code to be written which can return us **all possible combination and the combination will never conflict with other combinations.

Thanks in advance.

Mohammad Zeeshan
  • 825
  • 1
  • 9
  • 20

1 Answers1

1

You could take a brute force approach with a recursive function for collected pairs and a list of available pairs.

If a new pair is possible to get, take this pair and call the function again.

function getAllPairs(array) {
    var pairs = [];
    for (let i = 0; i < array.length - 1; i++) {
        for (let j = i + 1; j < array.length; j++) {
            pairs.push([array[i], array[j]]);
        }
    }
    return pairs;
}

function fill(pairs, result = []) {
    function check(array) {
        return array.every((s => a => a.every(v => !s.has(v) && s.add(v)))(new Set));
    }

    if (!pairs.length) return result;

    var left = result.slice(Math.floor(result.length / half) * half);

    for (let i = 0; i < pairs.length; i++) {
        if (!check([...left, pairs[i]])) continue;
        var newResult = fill([...pairs.slice(0, i), ...pairs.slice(i + 1)], [...result, pairs[i]]);
        if (newResult) return newResult; // i miss something like returnIf
    }
}

var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    half = data.length / 2,
    temp = fill(getAllPairs(data)),
    result = [],
    i = 0;

while (i < temp.length) result.push(temp.slice(i, i += half));

result.forEach(a => console.log(...a.map(a => a.map(v => v.toString().padStart(2, ' ')).join('|'))));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392