首页 > 解决方案 > 嵌套循环的动态数量(在 Javascript 中)

问题描述

我想生成所有可能的数字组合,其中n是最高的。

例如:

0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2

我目前的方法非常简单,只需n 个for 循环。
问题是,我不知道n

n = 3;
for (a=0; a <= n; a++) {
    for (b=0; b <= n; b++) {
        for (c=0; c <= n; c++) {
            console.log(`${a} ${b} ${c}`);
        }
    }
}

我需要一种动态生成这些循环的方法。



也欢迎任何其他产生所有可能性的方法。

标签: javascript

解决方案


您可以获取笛卡尔积的函数、所需符号数组和所需长度并返回此结果。

function getCombinations(signs, length) {
    const cartesian = array => array
        .reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
    
    return cartesian(Array.from({ length }, _ => signs));
}

console.log(getCombinations([1, 2, 3], 5).map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读