问题
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