/*
Was asked in airbnb phone screen
When you book on airbnb the total price is:
Total price = base price + service fee + cleaning fee + ...
input : array of decimals ~ X
output : array of int ~ Y
But they need to satisfy the condition:
sum(Y) = round(sum(x))
minmize (|y1-x1| + |y2-x2| + ... + |yn-xn|)
Example1:
input = 30.3, 2.4, 3.5
output = 30 2 4
Example2:
input = 30.9, 2.4, 3.9
output = 31 2 4
*/
/*
My Idea:
First, get the rounded sum -- our goal
Then, floor all the numbers
and get the floored sum
sort the floored numbers by their distance
until we reach the rounded number, increase our flooded number by one
*/
function roundNumbers(nums) {
const goal = Math.round(nums.reduce((a, b) => a + b))
const numsWithFloor = nums
.map(num => [num, Math.floor(num)])
.sort(([numA, flo])
const flooredNums = nums
.map((val, index) => ({val, index}))
.sort(({val: a}, {val: b}) => (b - Math.floor(b)) - (a - Math.floor(a)))
.map(value => ({...value, val: Math.floor(value.val)}))
const flooredSum = flooredNums.map(({val}) => val).reduce((a, b) => a + b)
for (let i = 0; i < sum - flooredSum; i++) {
flooredNums[i].val++
}
return flooredNums.sort(({index: a}, {index: b}) => a - b).map(({val}) => val)
}
console.log(roundNumbers([30.3, 2.4, 3.5]))
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.