Skip to content

Instantly share code, notes, and snippets.

@vitapluvia
Created July 2, 2017 04:20
Show Gist options
  • Save vitapluvia/f70e18b3dcce775dcf0a5a8d597ae58a to your computer and use it in GitHub Desktop.
Save vitapluvia/f70e18b3dcce775dcf0a5a8d597ae58a to your computer and use it in GitHub Desktop.
permutations
'use strict';
const permU = (ar) => {
if (ar.length <= 1) return [ar];
const first = ar[0];
const nPerm = permU(ar.slice(1));
return nPerm.reduce((acc, value) => {
for (let i=0; i <= value.length; ++i) {
const start = value.slice(0, i);
const tail = value.slice(i, value.length);
const perm = start.concat(first).concat(tail);
acc.push(perm);
}
return acc;
}, []);
};
// Test Permuation:
const ALPH = 'abcdefghijklmnopqrstuvwxyz';
const flat = ar => ar.join('');
for (let i=1; i <= 5; ++i)
console.log(`N ${i}: ${permU(ALPH.slice(0, i).split('')).map(flat)}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment