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

  • 相关阅读:
    使用CSS3实现超炫的Loading(加载)动画效果
    三种简洁的经典高效的DIV+CSS制作的Tab导航简析
    Span和Div的区别
    [总结]Jquery api 快速参考
    25个可遇不可求的jQuery插件
    基于单个 div 的 CSS 绘图
    一款基于jQuery的图片场景标注提示弹窗特效
    HTML5手机开发——滚动和惯性缓动
    发布一个高效的JavaScript分析、压缩工具 JavaScript Analyser
    CSS框架BluePrint
  • 原文地址:https://www.cnblogs.com/hiluna/p/8727266.html
Copyright © 2011-2022 走看看