【问题标题】:Given a list of recipes a list of owned ingredients, which algorithm is best to determine "Which ingredient could I add to access the most recipes?"给定食谱列表和拥有成分的列表,哪种算法最适合确定“我可以添加哪种成分来访问最多的食谱?”
【发布时间】:2021-11-28 16:25:33
【问题描述】:

我希望长标题能很好地解释问题。这感觉像是一个名义上的问题,所以我怀疑有一个已知的算法可以解决这个问题,或者它可能映射到 NP。

给定一本食谱

cookbook = {
    recipe1: [ingredient1, ingredient2, ingredient35],
    recipe2: [ingredient1, ingredient8, ingredient12], 
    recipe3: [ingredient10, ingredient22, ingredient35],
    ...
}

以及表格中的成分列表

ingredients = {
    ingredient1: true, //owned
    ingredient2: false, //unowned
    ingredient3: true,
    ...
}

哪种算法可以有效地回答“您可以添加哪种成分来完成最多的食谱?”

假设

  • 有大量的食谱和成分
  • 给定的食谱不会超过 10 种成分
  • 您可以按照自己认为合适的方式转换/操作数据
  • 评分标准是您制定算法的效率如何,该算法可以回答“鉴于我已经拥有该成分,我应该添加哪种成分来制作最多的食谱”
  • 一个人可以随意添加/删除成分,并且必须能够回答“哪种成分?”有效地提问
  • 现在可以忽略空间复杂度
  • 然后意图是设计一种数据结构 + 算法,无论计算复杂度如何,都允许快速查询。 “评分”是这些未来查询的速度

【问题讨论】:

  • 我怀疑将成分列表转换为位图效果会很好。对这些应用逐位数学运算速度很快,并且生成的答案相对于您的查询类型而言易于过滤。
  • 次要的挑剔:似乎您要求的是动态数据结构来响应各种查询,而不是单个算法。这是一个准确的改写吗?另外,您知道“添加/删除成分”查询与“最佳成分”查询的相对数量吗?任何数据结构都会在优化这两者之间进行权衡。
  • 是的,这样改写更好,我会修改问题。目的是格式化数据(即使这一步很昂贵),以便将来的调用尽可能快。

标签: algorithm performance graph-theory coding-efficiency


【解决方案1】:

伪代码

bestIngredient = 0
bestCount = 0
Loop I  over owned ingredients
   count = 0
   Loop R over recipes
       If I completes R
          increment count
   if count > bestCount
      bestCount = count
      bestIngredient = I

添加成分 I 时:

Loop R over recipies
    If R needs I 
    Add I to R

【讨论】:

  • 我认为你的意思是遍历非自有成分
  • 这是一个很好的解决方案,只是速度很慢。 O(unownedIngrediants * recipes) ~ O(n^2) 也许这是最好的,但我希望更快
【解决方案2】:
score = empty hashmap
for each R in recipes
  missing = empty list
  for each I in R
    if ingredients[i] = false
      missing += I
  if size(missing) = 1
    I = missing[0]
    score[I]++
result = choose key I in score with maximum value

【讨论】:

    【解决方案3】:

    从食谱中创建一个 trie。对于每个查询,递归查询的子序列和一个允许的通配符,遍历特里树。 (recipes 和 query 都应该以相同的方式对成分进行排序。)

    【讨论】:

      猜你喜欢
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多