Last active
August 11, 2021 09:50
-
-
Save JakobTischler/5d17d0333401f82991086d888823206f to your computer and use it in GitHub Desktop.
Returns a list of numbers as fractions of the input number. Eg. 23 in 6 parts = [ 4, 4, 4, 4, 4, 3 ] (smooth) or [ 8, 3, 3, 3, 3, 3 ] (tight).
This file contains 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
// Modes: | |
// "Smooth" spreads the number list so they are as close together as possible (+- 1). E.g. 23 in 6 parts = [ 4, 4, 4, 4, 4, 3 ] | |
// "Tight" has 1 number with a "rest" value, and the remaining numbers identical to each other. E.g. 23 in 6 parts = [ 8, 3, 3, 3, 3, 3 ] | |
const Mode = { | |
Smooth: 1, | |
Tight: 2, | |
}; | |
function getIntParts(number, numParts, mode = Mode.Smooth) { | |
const val = number / numParts; | |
const valFloor = Math.floor(val); | |
let ret = new Array(numParts).fill(valFloor); | |
if (val > valFloor) { | |
const remain = number - numParts * valFloor; | |
if (mode === Mode.Smooth) { | |
for (let index = 0; index < remain; index++) { | |
ret[index] += 1; | |
} | |
} else if (mode === Mode.Tight) { | |
ret[0] += remain; | |
} | |
} | |
return ret; | |
} | |
const testNum = 1003; | |
const testNumParts = 9; | |
const parts = getIntParts(testNum, testNumParts); | |
console.log({ testNum, testNumParts, parts }); | |
const parts2 = getIntParts(testNum, testNumParts, Mode.Tight); | |
console.log({ testNum, testNumParts, parts2 }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment