Created
February 10, 2017 23:24
-
-
Save dzek69/73da8311760417686e802425dea4e2a7 to your computer and use it in GitHub Desktop.
equally spreads number into array with n integer elements, equally filling unevens
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default (number, parts) => { | |
if (!parts) { | |
return []; | |
} | |
let left = number; | |
const result = []; | |
const fullMin = Math.floor(number / parts); | |
for (let i = 0; i < parts; i++) { | |
result.push(fullMin); | |
left -= fullMin; | |
} | |
let rest = left % parts; | |
const every = Math.floor(parts / rest); | |
let i = 0; | |
while (rest > 0) { | |
result[i] += 1; | |
rest -= 1; | |
i += every; | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment