zoukankan      html  css  js  c++  java
  • codewars--js--Pete, the baker

    问题描述:

    Pete likes to bake some cakes. He has some recipes and ingredients. Unfortunately he is not good in maths. Can you help him to find out, how many cakes he could bake considering his recipes?

    Write a function cakes(), which takes the recipe (object) and the available ingredients (also an object) and returns the maximum number of cakes Pete can bake (integer). For simplicity there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are simply 1 or 200). Ingredients that are not present in the objects, can be considered as 0.

    Examples:

    // must return 2
    cakes({flour: 500, sugar: 200, eggs: 1}, {flour: 1200, sugar: 1200, eggs: 5, milk: 200}); 
    // must return 0
    cakes({apples: 3, flour: 300, sugar: 150, milk: 100, oil: 100}, {sugar: 500, flour: 2000, milk: 2000});

    我的答案:

     1 function cakes(recipe, available) {
     2   // TODO: insert code
     3        var n=[];
     4         for( key in recipe){
     5           if (key in available){
     6             var num=Math.floor(available[key]/recipe[key]);
     7             n.push(num);
     8           }
     9           else{ return 0;}
    10         } 
    11       return parseInt(n.sort((x,y)=>x-y).slice(0,1)); //此处直接 return Math.min(n);
    12     }

    优秀答案:

    (1)

    1 function cakes(recipe, available) {
    2   return Object.keys(recipe).reduce(function(val, ingredient) {
    3     return Math.min(Math.floor(available[ingredient] / recipe[ingredient] || 0), val)
    4   }, Infinity)  
    5 }

    (2)

    1 const cakes = (needs, has) => Math.min(
    2   ...Object.keys(needs).map(key => Math.floor(has[key] / needs[key] || 0))
    3 )

    (1)键值数组

    (2)Object.keys()
    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

    Object.keys() 方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用 for...in 循环遍历该对象时返回的顺序一致 (两者的主要区别是 一个 for-in 循环还会枚举其原型链上的属性)

    var arr={3:"1",5:"2","a":"b",2:"5"};

    Object.keys(arr);   //返回 ["2", "3", "5", "a"]

    (3)for in 和 forEach

  • 相关阅读:
    神秘现象?多种情况比较
    [备忘]C++BUILDER的文件操作
    缘起
    [备忘]一个二维数组的冒泡排序
    无可救药地买入NDSL
    递归的实质
    [网游计划第九、十天]能力有限,做些小品
    大学有救
    struts2+convertion实现struts.xml的零配置
    BSD下的超级终端
  • 原文地址:https://www.cnblogs.com/hiluna/p/8727266.html
Copyright © 2011-2022 走看看