如何将库存食材列表与嵌套结构的菜谱食材列表比对?
解决方案:库存食材与菜谱匹配
核心逻辑拆解
- 遍历所有菜谱,检查该菜谱的全部食材是否都存在于库存列表中
- 统一字符串大小写,避免因大小写差异导致匹配失败
- 先修正代码里的拼写错误(比如
appel应为apple、potatato应为potato,否则会影响匹配结果)
具体实现步骤
- 将库存食材转成小写集合,提升后续查找效率
- 遍历菜谱列表,对每个菜谱的食材列表做检查
- 判断菜谱食材是否全部包含在库存中,筛选出可制作的菜谱
完整代码示例
List<RecipeList> recipesList = [ RecipeList(recipeName: "Cake", itemNames: ["banana", "apple"]), // 修正拼写:appel → apple RecipeList(recipeName: "Soup", itemNames: ["potato", "egg"]), // 修正拼写:potatato → potato RecipeList(recipeName: "Sandwich", itemNames: ["Toast", "Sausage", "Ketchup"]), RecipeList(recipeName: "Pizza", itemNames: ["Tomato", "Mushroom"]), ]; List<String> inventory = ["coke", "egg", "banana", "apple"]; class RecipeList { String? recipeName; List<String>? itemNames; RecipeList({this.recipeName, this.itemNames}); } void main() { // 转小写集合,快速查找 final lowerCaseInventory = inventory.map((item) => item.toLowerCase()).toSet(); // 筛选可制作的菜谱 List<RecipeList> cookableRecipes = recipesList.where((recipe) { if (recipe.itemNames == null) return false; // 菜谱食材转小写后,检查是否全部在库存中 return recipe.itemNames!.every((item) => lowerCaseInventory.contains(item.toLowerCase())); }).toList(); // 输出结果 print("可制作的菜谱:"); for (var recipe in cookableRecipes) { print("- ${recipe.recipeName}"); } }
额外扩展方向
- 如果需要找部分匹配的菜谱,把
every换成any,或者统计匹配食材的数量占比 - 可以给菜谱添加匹配度评分,按评分排序展示
- 库存转
Set是为了优化大数量场景下的查找性能
内容的提问来源于stack exchange,提问作者Reen
相关产品推荐
相关产品推荐

