Skip to content

Instantly share code, notes, and snippets.

@gartenfeld
Created July 9, 2015 23:50
Show Gist options
  • Save gartenfeld/47a35bb2d43dc6204033 to your computer and use it in GitHub Desktop.
Save gartenfeld/47a35bb2d43dc6204033 to your computer and use it in GitHub Desktop.
Generating permutations and logging each step.
function permutator(inputArr) {
// the output matrix of all permutations
var results = [];
// takes the array of character set
function permute(columnOptions, path) {
var place, newPath, path = path || [];
// for a given row
// go through the options for "which column"
console.log('available columns: ' + JSON.stringify(columnOptions));
console.log('given path: ' + JSON.stringify(path));
for (var i = 0; i < columnOptions.length; i++) {
// take one option out of the available options
// this also alters the options array
place = columnOptions.splice(i, 1)[0];
console.log('taking out option #' + i.toString() + ': ' + JSON.stringify(place));
console.log('truncated options pool: ' + JSON.stringify(columnOptions));
console.log('adding option ' + JSON.stringify(place) +' to given path ' + JSON.stringify(path));
newPath = path.concat(place);
console.log(' => new path: ' + JSON.stringify(newPath));
// if we placed all pieces / reached the end
if (columnOptions.length === 0) {
// add the path to the collection of complete path
console.log('all options used, adding to results: ' + JSON.stringify(newPath));
results.push(newPath);
}
console.log('recursive call: options:' + JSON.stringify(columnOptions) + ', given path:' + JSON.stringify(newPath));
permute(columnOptions.slice(), newPath);
// putting it back into the options array
columnOptions.splice(i, 0, place);
console.log('putting the option ' + JSON.stringify(place) + ' back');
console.log('restored options pool: ' + JSON.stringify(columnOptions));
}
return results;
}
return permute(inputArr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment