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

  • 相关阅读:
    Spring中的Bean相关问题
    请谈一下spring bean的生命周期
    请谈一谈IOC中的继承和Java中的继承有什么区别
    谈谈你对Spring IOC和DI的理解,以及它们的区别
    Spring中用到了哪些设计模式
    JAVA自学笔记11
    JAVA自学笔记14
    JAVA自学笔记12
    JAVA自学笔记15
    JAVA自学笔记18
  • 原文地址:https://www.cnblogs.com/hiluna/p/8727266.html
Copyright © 2011-2022 走看看