Skip to content

Instantly share code, notes, and snippets.

@animatedlew
Created March 4, 2019 14:14
Show Gist options
  • Select an option

  • Save animatedlew/9f18ca2ff8a215c7da52fab64470b243 to your computer and use it in GitHub Desktop.

Select an option

Save animatedlew/9f18ca2ff8a215c7da52fab64470b243 to your computer and use it in GitHub Desktop.

Revisions

  1. animatedlew created this gist Mar 4, 2019.
    32 changes: 32 additions & 0 deletions strperm.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@

    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');