Javascript NodeJS ES6 combination/permutations algorithm

落花浮王杯 提交于 2019-12-13 08:56:23

问题


Little challenge.


Goal (nodeJS, loop is an * interator function using "yield" strategy)

var str;
var minChars = 1;
var maxChars = 10;
for (str of loop('abcdefghijklmnopqrstuvwxyz',minChars,maxChars)) {
    console.log(str);
}

Constraints:

  • Only generate string combinations length between minChars and maxChars
  • Must not consumme all memory (Array in store not allowed)
  • Must use ES6 iterators, so step by step is possible
  • Recursion is allowed
  • Can provide billions of combination

Sample output (order is important):

a
b
c
[...]
z
aa
ab
ac
[...]
aaa
aab
aac
[...]
aba
abb
abc
[...]
bza
bzb
bzc
[...]
zzzzzzzzzz

回答1:


Trivial solution:

function* loop(alphabet, min, max) {
    if (min > max) throw new RangeError("max needs to be greater than min");
    if (min <= 0)
        yield "";
    if (max > 0)
        for (const rest of loop(alphabet, min-1, max-1))
            for (const a of alphabet)
                yield rest+a;
}

(Babel demo)



来源:https://stackoverflow.com/questions/34163786/javascript-nodejs-es6-combination-permutations-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!