javascript - 获取在javascript中值叠加仍然较少的数组键

标签 javascript algorithm node.js logic

我有一个问题,我试图计算有多少个 child 的年龄(作为关键),如下所示,但我们想要 根据 a 获取大 child 组(在本例中是大 child 的组是 4 和 2) child >= 4 个 child 组我想获得可以组成大 child 组的最大年龄数。

问题我如何获得新创建的组中最大年龄小于/等于 4 个 child 的年龄?

这就是我们在输入中得到的内容

max_bigest_kids_in_group = 4
kids object = {
//age 0 have 7 kids
'0' : 7
//age 1 have 3 kids
'1' : 3
//age 2 have 2 kids
'2' : 2 
//age 4 have 1 kids
'4' : 1
//lets say there is no age 3 or 5,6 and so on.
}

这是我目前在 psudo 中尝试过并目前所做的

try    biggest  next biggest 
    ('4' = 1) + ('2' = 2)  (oke becouse 1+2 is 3 >= 4) save array [4 and 2]
try    biggest  next biggest next biggest
    ('4' = 1) + ('2' = 2) + ('1' = 3) (not oke becouse 1+2+3 is 6 >= 4) stop becouse its more then x = 4
    get array [4 and 2] 

    // expected result is {'4','2'} or ['4','2'] so if max_bigest_kids_in_group = 6 then it will be ['4','2','1']

我们怎样才能得到预期的结果?在 JavaScript 中

ps。抱歉,如果标题不准确,如果有任何建议,请评论或编辑。

最佳答案

这很简单。只需对 children 进行循环,就像在伪代码中一样。

var kids = {
   '0' : 7, //age 0 have 7 kids
   '1' : 3, //age 1 have 3 kids
   '2' : 2, //age 2 have 2 kids
   '4' : 1  //age 4 have 1 kids
};
function getAgesOfOldestKids(n) {
/* get: {number} how many kids */

    // lets begin with some magic to find out the maximum age in the set
    // you might code this with a for-in-loop over kids
    var max = Math.max.apply(null, Object.keys(kids));

    var ages = []; // ages of the kids in the result
    var count = 0; // how many kids are in the set
    for (var i=max; i>=0; i--)
        if (i in kids) { // age level exists
            count += kids[i]; // add number of kids
            if (count > n) // kids in the set are more than allowed
                return ages; // break the loop
            else
                ages.push(i); // add this age step to the result
        }
    return ages; // there may be less children than requested
}

> getAgesOfOldestKids(4)
["4", "2"]

// a trick to get the number of kids in the result:
> var ages = [4, 2];
> ages.reduce(function(n, age){return n+kids[age]}, 0)
3

其他可能且更短的解决方案,直接在 child 的 key 上循环:

function getAgesOfOldestKids(n) {
/* get: {number} how many kids */

    // ages, sorted descending
    var ages = Object.keys(kids).sort(function(a,b){return b-a;});

    var count = 0; // how many kids are in the set
    for (var i=0; i<ages.length-1 && count <= n; i++)
        count += kids[ages[i]]; // add number of kids
    return ages.slice(0, i-1);
}

关于javascript - 获取在javascript中值叠加仍然较少的数组键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11414113/

相关文章:

algorithm - 我的 RSA 算法只适用于非常短的单词

algorithm - case 3 为什么要加一个常量?

javascript - 如何将 JavaScript 添加到 FPDF 中?

javascript - 如何简化下面的函数?

javascript - 在启用分页的情况下记住 ExtJS 网格中的选择

macos - 重启后找不到 npm 命令

function - 在 Node.js 中使用 HTML Helpers?

javascript - 如何在ajax进程完成之前创建延迟?

algorithm - 以最佳方式减少序列

node.js - 如何自动化 Google Drive Docs OCR 功能?