Javascript NodeJS ES6组合/排列算法 [英] Javascript NodeJS ES6 combination/permutations algorithm

查看:460
本文介绍了Javascript NodeJS ES6组合/排列算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小挑战

目标(nodeJS,循环是使用yield策略的* interator函数) p>

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:


  • 只生成minChars和maxChars之间的字符串组合长度

  • 不能耗尽所有内存)

  • 必须使用ES6迭代器,所以一步一步可以

  • 允许递归

  • 可以提供数十亿的组合

  • 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


推荐答案

琐碎解决方案:

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

这篇关于Javascript NodeJS ES6组合/排列算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆