javascript - 嵌套循环的动态数量(在 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}`);
}
}
}
我需要一种动态生成这些循环的方法。
也欢迎任何其他产生所有可能性的方法。
解决方案
您可以获取笛卡尔积的函数、所需符号数组和所需长度并返回此结果。
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; }
推荐阅读
- r - 有什么方法可以使用本地 R 数据框创建 .sqlite 文件?
- javascript - 在此服务器上未找到请求的 URL /about-us
- flutter - 为什么要出售此消息,setState() 或 markNeedsBuild() 在构建 obx Getx 期间调用
- php - laravel 队列作业,调度两个参数
- firebase - 无法在flutter中访问Firebase Firestore doc的字段
- flutter - FocusScope.of(context!).unfocus() 没有足够快地触发 Focus 小部件的 onFocusChange;
- android - 像what'app这样的聊天应用程序中的未读消息计数
- robotframework - 获取 InvalidElementStateException:消息:无效元素状态
- r - 合并具有不同年龄形式的两个数据框
- sql - Oracle APEX 应用程序流程 > 在计算/验证之前提交时在交互式网格上不起作用