-3

having trouble wrapping my head around how to code something up, I've done a bit of googling but haven't found anything that does this specific task. I've had some ideas but none of them seem practical, and I'm afraid I'd miss some combinations.

Imagine you have an array of 6 people

var people = ['bob', 'joe', 'jeff', 'sandy', 'jessica', 'april'];

And an array of 6 shirts

var shirts = ['red', 'blue', 'green', 'yellow', 'purple', 'white'];

How can we generate a list of every possible combination of these 6 people wearing these 6 shirts? Something like:

[ ['bob', 'red'], ['joe', 'blue'], ['jeff', 'green'], ['sandy','yellow'], ['jessica', 'purple'], ['april', 'white'] ]
[ ['bob', 'blue'], ['joe', 'red'], ['jeff', 'green'], ['sandy','yellow'], ['jessica', 'purple'], ['april', 'white'] ]
...
..
.

Any help or links would be greatly appreciated!

Caleb O'Leary
  • 753
  • 6
  • 10

2 Answers2

1

Find all permutations of shirts. The index of each permuted shirt maps directly to the person wearing it. Example:

for (let permutation of permute(shirts)) {
  let combination = permutation.map((shirt, index) => [people[index], shirt]);
  ...
}
Community
  • 1
  • 1
le_m
  • 19,302
  • 9
  • 64
  • 74
  • 1
    Thanks le_m, and thanks for sticking around even though I got downvoted in to oblivion for some reason. Perhaps I didn't ask well, either way here's what I came up with thanks to your comment https://jsfiddle.net/3Lc5sabb/ – Caleb O'Leary Mar 24 '17 at 16:16
  • You are welcome! The question is well stated, but the answer might be too obvious for seasoned and sometimes trigger happy SO veterans. Just guessing though... – le_m Mar 24 '17 at 16:21
1

As @le_m was writing his answer I was testing a solution in JSFiddle. Actually I think I was using his/hers's own function as it's the fastest permutation function in find all permutations page. So I guess I'll just leave it here in case it's helpful.

function permutate_le_m(permutation) {
  var length = permutation.length,
    result = new Array([0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600][length]),
      c = new Array(length).fill(0),
      i = 1,
      j = 1;

  result[0] = permutation.slice();
  while (i < length) {
    if (c[i] < i) {
      var k = (i % 2) ? c[i] : 0,
          p = permutation[i];
      permutation[i] = permutation[k];
      permutation[k] = p;
      ++c[i];
      i = 1;
      result[j] = permutation.slice();
      ++j;
    } else {
      c[i] = 0;
      ++i;
    }
  }
  return result;
}

var people = ['bob', 'joe', 'jeff', 'sandy', 'jessica', 'april']
var shirts = ['red', 'blue', 'green', 'yellow', 'purple', 'white'];
var pshirts = permutate_le_m(shirts);
var combined = pshirts.map(perm=>perm.map((elem, ix)=>[people[ix], elem]));
console.log(combined.length);
console.log(combined);

JSFiddle: https://jsfiddle.net/xzr4q7a9/1/

Community
  • 1
  • 1
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73