Skip to content

Instantly share code, notes, and snippets.

@md2perpe
Created January 1, 2014 18:54
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save md2perpe/8210411 to your computer and use it in GitHub Desktop.
Save md2perpe/8210411 to your computer and use it in GitHub Desktop.
Function for generating permutations of a list.
function permutations(list)
{
// Empty list has one permutation
if (list.length == 0)
return [[]];
var result = [];
for (var i=0; i<list.length; i++)
{
// Clone list (kind of)
var copy = Object.create(list);
// Cut one element from list
var head = copy.splice(i, 1);
// Permute rest of list
var rest = permutations(copy);
// Add head to each permutation of rest of list
for (var j=0; j<rest.length; j++)
{
var next = head.concat(rest[j]);
result.push(next);
}
}
return result;
}
@stuart-clark-45
Copy link

stuart-clark-45 commented Dec 8, 2020

Here's a TS version

export function permutations<T>(list: T[]): T[][] {
  // Empty list has one permutation
  if (list.length === 0) return [[]];
  const result: T[][] = [];
  for (let i = 0; i < list.length; i++) {
    // Clone list (kind of)
    const copy = Object.create(list);
    // Cut one element from list
    const head = copy.splice(i, 1);
    // Permute rest of list
    const rest = permutations(copy);
    // Add head to each permutation of rest of list
    for (let j = 0; j < rest.length; j++) {
      const next = head.concat(rest[j]);
      result.push(next);
    }
  }
  return result;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment