Skip to content

Instantly share code, notes, and snippets.

@mschultheiss83
Created January 8, 2015 17:55
Show Gist options
  • Save mschultheiss83/98c838eaab2b9ca8c3a6 to your computer and use it in GitHub Desktop.
Save mschultheiss83/98c838eaab2b9ca8c3a6 to your computer and use it in GitHub Desktop.
js permutation functions
/*jslint sloppy:true, white:true, vars:true, plusplus:true */

var permutation = function (collection){
    var current,
        subarray,
        result = [],
        currentArray = [],
        newResultArray = [];

    if (collection.length){
        current = collection.shift();
        result = permutation(collection);

        currentArray.push(current);

        result.map(function(list) {
            newResultArray.push(list.slice(0));
            list.push(current);
        });

        result.push(currentArray);
        result = result.concat(newResultArray);
    }

    return result;
};

console.log(permutation(['a','b','c','d'])
            .join('\n'));
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment