You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将库存食材列表与嵌套结构的菜谱食材列表比对?

解决方案:库存食材与菜谱匹配

核心逻辑拆解

  • 遍历所有菜谱,检查该菜谱的全部食材是否都存在于库存列表中
  • 统一字符串大小写,避免因大小写差异导致匹配失败
  • 先修正代码里的拼写错误(比如appel应为apple、potatato应为potato,否则会影响匹配结果)

具体实现步骤

  1. 将库存食材转成小写集合,提升后续查找效率
  2. 遍历菜谱列表,对每个菜谱的食材列表做检查
  3. 判断菜谱食材是否全部包含在库存中,筛选出可制作的菜谱

完整代码示例

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:05:43