Created
March 4, 2019 14:14
-
-
Save animatedlew/9f18ca2ff8a215c7da52fab64470b243 to your computer and use it in GitHub Desktop.
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
function perm1(input /* string */) { | |
if (!input.length) return [input]; | |
let results = input.split('').reduce((results, c) => { | |
let tail = input.split(c).join(''); | |
return results.concat(perm1(tail).map(p => c + p)); | |
}, []); | |
return results; | |
} | |
function perm2(input /* string */) { | |
const len = input.length; | |
if (!len) return [input]; | |
let results = []; | |
for (let i = 0; i < len; i++) { | |
let head = input[i]; | |
let tail = input.split(head).join(''); | |
results = results.concat(perm2(tail).map(p => head + p)); | |
} | |
return results; | |
} | |
let now = Date.now(); | |
for (let i = 0; i < 100000; i++) perm1('abcd'); | |
let later = Date.now(); | |
console.log((later - now) / 1000, 'seconds'); | |
now = Date.now(); | |
for (let i = 0; i < 100000; i++) perm2('abcd'); | |
later = Date.now(); | |
console.log((later - now) / 1000, 'seconds'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment