![](/img/trans.png)
[英]How can I change the ingredients in the recipe to correspond with the user input?
[英]I have a an array of recipe ingredients with different serving amounts, how can I get all possible combinations of these ingredients?
我想复制具有相同成分的食谱,但每种成分的数量不同。
这是我的成分对象:
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是我想要增加的数量, maxAmount是我想要停止增加该成分的数量。
到目前为止,我创建了一个循环,将所有单一成分的变化放入数组中:
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);
}
};
这给了我这个结果:
[
[
{
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,
},
],
];
现在,我如何从这个数组中创建所有可能的组合?
副本示例:
将您已经生成的数组作为输入( intermediate
),您可以执行以下操作:
const allCombinations = intermediate.reduce(
(acc, ingredientVariants) => (
acc.flatMap(prefix => (
ingredientVariants.map(v => [...prefix, v])
))
),
[[]],
)
这在性能方面并不是很好,因为我们复制了很多数组并创建了很多匿名函数,但鉴于您的输出无论如何都是指数的,这并不重要。
我们从 0 种成分的所有组合表( [[]]
)开始,然后我们有 1 种成分、2 种成分的所有组合,依此类推。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.