[英]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.