• 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

  • 相关阅读:
    使用WebViewJavascriptBridge与UIWebView交互
    使用UICollectionView
    UIButton中的**EdgeInsets是做什么用的?
    [翻译] CoreImage-with-EAGLContext
    [翻译] SAMCoreImageView
    [翻译] NSImage+HHTint
    使用iCarousel的旋转木马效果请求图片
    使用TFHpple解析html
    使用MapKit框架(持续更新)
    定制UITabBar显示样式
  • 原文地址:https://www.cnblogs.com/hiluna/p/8727266.html
Copyright © 2020-2023  润新知