Get all possible set of combinations of two arrays as an array of arrays with JavaScript

后端 未结 2 1412
渐次进展
渐次进展 2021-01-13 17:52

Please note: the linked question, \"How can I create every combination possible for the contents of two arrays?\" does not solve this particular qu

2条回答
  •  梦谈多话
    2021-01-13 18:40

    [[A, 1], [B, 2]]

    is the same as

    [[B, 2], [A, 1]]

    in your case, which means that the solution depends on what you pair to the first elements of your array. You can pair n different elements as second elements to the first one, then n - 1 different elements as second elements to the second one and so on, so you have n! possibilities, which is the number of possible permutations.

    So, if you change the order of the array elements but they are the same pair, they are equivalent, so you could view the first elements as a fixed ordered set of items and the second elements as the items to permutate.

    Having arr1 = [a1, ..., an] and arr2 = [b1, ..., bn] we can avoid changing the order of a1. So, you permutate the inner elements and treat the outer elements' order as invariant, like:

    const permutations = function*(elements) {
      if (elements.length === 1) {
        yield elements;
      } else {
        let [first, ...rest] = elements;
        for (let perm of permutations(rest)) {
          for (let i = 0; i < elements.length; i++) {
            let start = perm.slice(0, i);
            let rest = perm.slice(i);
            yield [...start, first, ...rest];
          }
        }
      }
    }
    
    var other = ['A', 'B', 'C'];
    var myPermutations = permutations(['X', 'Y', 'Z']);
    var done = false;
    while (!done) {
        var next = myPermutations.next();
        if (!(done = next.done)) {
            var output = [];
            for (var i = 0; i < next.value.length; i++) output.push([other[i], next.value[i]]);
            console.log(output);
        }
    }
    

提交回复
热议问题