gpt4 book ai didi

javascript - 获取在 javascript 中仍然较少的值堆栈的数组键

转载 作者:搜寻专家 更新时间:2023-10-31 23:43:47 24 4
gpt4 key购买 nike

我有一个问题,我正在尝试计算有多少 child 的年龄(作为关键)如下,但我们想根据kids >= 4 kids group 我想获得可以组成大 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中

附言。抱歉,如果标题不是那么准确,如果有任何建议,请评论或编辑。

最佳答案

这很简单。就像在你的伪代码中一样,在 child 身上循环。

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

其他可能且更短的解决方案,直接在 children 的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com