[英]I have a an array of recipe ingredients with different serving amounts, how can I get all possible combinations of these ingredients?
I want to copy recipe with same ingredients, but with varying quantities of each ingredient.我想复制具有相同成分的食谱,但每种成分的数量不同。
Here is my ingredients object:这是我的成分对象:
const ingredientsToStretch2 = [
{
productName: "Strawberries, raw",
amount: 350,
numberOfServings: 350,
servingQuantity: 1,
incrementSize: 2,
maxAmount: 354,
},
{
productName: "Blueberries, raw",
amount: 100,
numberOfServings: 100,
servingQuantity: 1,
incrementSize: 2,
maxAmount: 104,
},
{
productName: "Blackberries, raw",
numberOfServings: 100,
amount: 100,
servingQuantity: 1,
incrementSize: 2,
maxAmount: 104,
},
];
incrementSize is the number that I want to increase the amount by, maxAmount is the amount where I want to stop incrementing that ingredient. incrementSize是我想要增加的数量, maxAmount是我想要停止增加该成分的数量。
So far, I created a loop that puts all single ingredient variations into array:到目前为止,我创建了一个循环,将所有单一成分的变化放入数组中:
const handleStretch = () => {
let stretchedRecipes = [];
for (let i = 0; i < ingredientsToStretch.length; i++) {
let combinations = [];
const gramIncrementSize = ingredientsToStretch[i].incrementSize;
const maxGramSize = ingredientsToStretch[i].maxAmount;
const initialNumberOfServings =
ingredientsToStretch[i].numberOfServings + gramIncrementSize;
for (
let j = initialNumberOfServings;
j <= maxGramSize;
j += gramIncrementSize
) {
combinations.push({
productName: ingredientsToStretch[i].productName,
numberOfServings: j,
});
}
stretchedRecipes.push(combinations);
}
};
This gives me this result:这给了我这个结果:
[
[
{
productName: "Strawberries, raw",
numberOfServings: 352,
},
{
productName: "Strawberries, raw",
numberOfServings: 354,
},
],
[
{
productName: "Blueberries, raw",
numberOfServings: 102,
},
{
productName: "Blueberries, raw",
numberOfServings: 104,
},
],
[
{
productName: "Blackberries, raw",
numberOfServings: 102,
},
{
productName: "Blackberries, raw",
numberOfServings: 104,
},
],
];
Now, how do I create all possible combinations out of this array?现在,我如何从这个数组中创建所有可能的组合?
example of copies:副本示例:
Taking the array you already generated as input ( intermediate
), you can do:将您已经生成的数组作为输入(
intermediate
),您可以执行以下操作:
const allCombinations = intermediate.reduce(
(acc, ingredientVariants) => (
acc.flatMap(prefix => (
ingredientVariants.map(v => [...prefix, v])
))
),
[[]],
)
This is not great performance-wise, as our copies the arrays a lot and creates lots of anonymous functions, but given that your output is exponential anyway, it shouldn't really matter.这在性能方面并不是很好,因为我们复制了很多数组并创建了很多匿名函数,但鉴于您的输出无论如何都是指数的,这并不重要。
We start with table of all combinations of 0 ingredients ( [[]]
), then we have all combinations with 1 ingredient, 2 ingredients, and so on.我们从 0 种成分的所有组合表(
[[]]
)开始,然后我们有 1 种成分、2 种成分的所有组合,依此类推。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.