Created
July 2, 2017 04:20
-
-
Save vitapluvia/f70e18b3dcce775dcf0a5a8d597ae58a to your computer and use it in GitHub Desktop.
permutations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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