Skip to content

Instantly share code, notes, and snippets.

@williscool
Forked from md2perpe/permutations.js
Last active January 21, 2017 04:42
Show Gist options
  • Save williscool/2cadbde4a0386db81271 to your computer and use it in GitHub Desktop.
Save williscool/2cadbde4a0386db81271 to your computer and use it in GitHub Desktop.

Revisions

  1. williscool revised this gist Feb 10, 2016. 1 changed file with 21 additions and 29 deletions.
    50 changes: 21 additions & 29 deletions permutations.js
    Original file line number Diff line number Diff line change
    @@ -1,30 +1,22 @@
    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;
    // permutations(["c","a","t"])
    function permutations(array){

    if (array.length === 0) return [[]];

    var perms = [];

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

    var copy = array.slice(0);
    var prefix = copy.splice(i,1);

    var rest = permutations(copy);

    for(var j = 0; j < rest.length ; j++) {
    perms.push(prefix.concat(rest[j]));
    }

    }

    return perms;
    }
  2. @md2perpe md2perpe created this gist Jan 1, 2014.
    30 changes: 30 additions & 0 deletions permutations.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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;
    }