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

  • 相关阅读:
    框架-Eureka:百科
    发布机制-灰度发布-例子:Windows
    发布机制-灰度发布-例子:QZone
    发布机制-灰度发布-例子:Gmail Labs
    发布机制:金丝雀发布、滚动发布、蓝绿发布到底有什么差别?关键点是什么?
    发布机制:金丝雀发布、滚动发布、蓝绿发布到底有什么差别?关键点是什么?2
    发布机制-影子测试:百科
    再探“指针”奥秘--换个角度看“指针”!
    uva 11646
    S3C2410 实验三——跑马灯实验
  • 原文地址:https://www.cnblogs.com/hiluna/p/8727266.html
Copyright © 2011-2022 走看看