-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.js
40 lines (33 loc) · 1.2 KB
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* @param {{type: string, weightCapacity: number}[]} reindeerTypes
* @param {{country: string, weight: number}[]} gifts
* @returns {{country: string, reindeers: { type: string, num: number }[]}[]}
*/
const howManyReindeers = (reindeerTypes, gifts) => {
const getReindeers = (/** @type {number} */ weight) => {
const allowedReindeersTypes = reindeerTypes.filter(
reindeerType => reindeerType.weightCapacity < weight
)
let totalWeightCapacity = allowedReindeersTypes.reduce(
(acc, reindeerType) => acc + reindeerType.weightCapacity,
0
)
return allowedReindeersTypes
.map(reindeerType => {
const num = Math.floor(weight / totalWeightCapacity)
weight -= num * reindeerType.weightCapacity
totalWeightCapacity -= reindeerType.weightCapacity
return {
type: reindeerType.type,
num,
}
})
.filter(reindeerType => reindeerType.num > 0)
}
reindeerTypes.sort((a, b) => b.weightCapacity - a.weightCapacity)
return gifts.map(gift => ({
country: gift.country,
reindeers: getReindeers(gift.weight),
}))
}
export {howManyReindeers}