LinDaiDai/niubility-coding-js

🌶️第3期第2题:创建一个函数batches返回能烹饪出面包的最大值

Opened this issue · 0 comments

创建一个函数batches返回能烹饪出面包的最大值

(题目来源:https://github.com/30-seconds/30-seconds-of-interviews)

/**
batches函数接收两个参数:
1. recipe 制作一个面包需要的各个材料的值
2. available 现有的各个材料的值
要求传入 recipe 和 available,然后根据两者计算出能够烹饪出面包的最大值
**/

// 0个面包,因为 butter黄油需要50ml,但是现在只有48ml
batches(
  { milk: 100, butter: 50, flour: 5 },
  { milk: 132, butter: 48, flour: 51 }
)
batches(
  { milk: 100, butter: 4, flour: 10 },
  { milk: 1288, butter: 9, flour: 95 }
)

// 1个面包
batches(
  { milk: 100, butter: 50, flour: 10 },
  { milk: 198, butter: 52, flour: 10 }
)

// 2个面包
batches(
  { milk: 2, butter: 40, flour: 20 },
  { milk: 5, butter: 120, flour: 500 }
)

这道题的解题思路其实就是比较recipeavailable两个对象的每一个属性值,用后者的属性值除以前者的属性值,然后得到一个数,例如0个面包中的:

  • available.milk / recipe.milk,得到1.32
  • available.butter / recipe.butter,得到0.96
  • available.flour / recipe.flour,得到10.2

然后取三个结果中的最小值0.96,再向下取整,得出最终能制作的面包个数为0

所以我们可以得出第一种解题方法:

const batches = (recipe, available) =>
  Math.floor(
    Math.min(...Object.keys(recipe).map(k => available[k] / recipe[k] || 0))
  )

过程分析:

  • Object.keys(recipe),迭代recipe对象,得到所有的key['milk', 'butter', 'flour']
  • 之后使用map遍历刚刚所有的key,并返回available[k]/recipe[k]的值:[1.32, 0.96, 10.2]
  • 需要得出上面一步数组中的最小值,所以可以使用Math.min(...arr)方法来获取
  • 最后将最小值0.96向下取整得到0

当然这道题你也可以使用Object.entries(),效果是一样的:

const batches = (recipe, available) =>
  Math.floor(
    // Math.min(...Object.keys(recipe).map(k => available[k] / recipe[k] || 0))
    Math.min(...Object.entries(recipe).map(([k, v]) => available[k] / v || 0))
  )