将计数器添加到 javascript 数组的 n 个组合
add counter to the n combinations of javascript array
此程序应输出数组中元素的多种可能组合。我没有做的是在左侧为每种可能的组合添加一个计数器。第一个组合是“001”,第二个组合是“002”,依此类推,直到最后一个。我尝试以多种方式使用 for 循环和 while-do 来做到这一点,但任何尝试都失败了。
function combine(a, b, c) {
if (b === 0) {
console.log(three.join(" "));
return;
}
for (var i = c; i <= a.length - b; i++) {
three[three.length - b] = a[i];
combine(a, b - 1, i + 1);
}
}
const vegetables = ["carrot", "tomatoes", "potatoes", "celery", "pepper"];
const three = [];
three.length = 4;
combine(vegetables, three.length, 0);
您可以使用 padStart
生成您要查找的内容。像这样
const vegetables = ["carrot", "tomatoes", "potatoes", "celery", "pepper"];
const three = [];
three.length = 4;
let counter = 1;
function combine(a, b, c) {
if (b === 0) {
const counterForPrint = (counter++).toString().padStart(3, "0");
console.log(`${counterForPrint} ${three.join(" ")}`);
return;
}
for (let i = c; i <= a.length - b; i++) {
three[three.length - b] = a[i]; combine(a, b - 1, i + 1);
}
}
combine(vegetables, three.length, 0);
顺便说一句,您可以使用一些库来生成组合。它使事情变得非常清晰,让您专注于实际逻辑。像这样
const Combinatorics = require("js-combinatorics");
const vegetables = ["carrot", "tomatoes", "potatoes", "celery", "pepper"];
const possibleCombinations = Combinatorics.permutation(vegetables);
let counter = 1;
possibleCombinations.forEach(element => {
const counterForPrint = (counter++).toString().padStart(3, "0");
console.log(`${counterForPrint} ${element}`);
});
此程序应输出数组中元素的多种可能组合。我没有做的是在左侧为每种可能的组合添加一个计数器。第一个组合是“001”,第二个组合是“002”,依此类推,直到最后一个。我尝试以多种方式使用 for 循环和 while-do 来做到这一点,但任何尝试都失败了。
function combine(a, b, c) {
if (b === 0) {
console.log(three.join(" "));
return;
}
for (var i = c; i <= a.length - b; i++) {
three[three.length - b] = a[i];
combine(a, b - 1, i + 1);
}
}
const vegetables = ["carrot", "tomatoes", "potatoes", "celery", "pepper"];
const three = [];
three.length = 4;
combine(vegetables, three.length, 0);
您可以使用 padStart
生成您要查找的内容。像这样
const vegetables = ["carrot", "tomatoes", "potatoes", "celery", "pepper"];
const three = [];
three.length = 4;
let counter = 1;
function combine(a, b, c) {
if (b === 0) {
const counterForPrint = (counter++).toString().padStart(3, "0");
console.log(`${counterForPrint} ${three.join(" ")}`);
return;
}
for (let i = c; i <= a.length - b; i++) {
three[three.length - b] = a[i]; combine(a, b - 1, i + 1);
}
}
combine(vegetables, three.length, 0);
顺便说一句,您可以使用一些库来生成组合。它使事情变得非常清晰,让您专注于实际逻辑。像这样
const Combinatorics = require("js-combinatorics");
const vegetables = ["carrot", "tomatoes", "potatoes", "celery", "pepper"];
const possibleCombinations = Combinatorics.permutation(vegetables);
let counter = 1;
possibleCombinations.forEach(element => {
const counterForPrint = (counter++).toString().padStart(3, "0");
console.log(`${counterForPrint} ${element}`);
});