I want to create an array which the sum of its positions gives as result the specific number.
The bigger numbers have to be filled from the start of the array and filled with 0 if needed and distributed as equal as possible.
For example, the expected result of some scenarios:
const array = new Array(4);
const number = 4;
// Expected result -> [1, 1, 1 ,1]
const array = new Array(5);
const number = 17;
// Expected result -> [4, 4, 3, 3 ,3]
const array = new Array(7);
const number = 2;
// Expected result -> [1, 1, 0, 0, 0, 0, 0]
What's the most efficient way to get this array using Javascript?
Note that the examples are presented with low numbers. A real example would use bigger numbers, like:
const array = new Array(52);
const number = 3215654;
And about the possible duplicated question, this one requires a different result order that the question pointed by other users, so that logic isn't feasible here.
I wanted to attempt this out of sheer curiosity, Here's what I have come up with:
const arrayLength = 5;
let number = 17;
const arr = [];
for(let i=arrayLength; i>0; i--){
const n = Math.ceil(number/i);
arr.push(n);
number -= n;
}
console.log(arr);//[ 4, 4, 3, 3, 3 ]
Dividing the number in equal parts seems to be the answer.
You could create a function that takes your two constraints as arguments. Inside that function you create a simple loop to iterate over your targetLength.
A simple example could look like this:
function buildArray(length, target) {
let result = [];
for(; length > 0; length--) {
let val = Math.ceil(target/length);
result.push(val);
target -= val;
}
return result;
}
buildArray(4, 4); // -> [1, 1, 1, 1]
buildArray(5, 17); // -> [4, 4, 3, 3, 3]
buildArray(7, 2); // -> [1, 1, 0, 0, 0, 0, 0]
Edit: Based on your provided example in your edit the result should be
buildArray(52, 3215654); // ->[61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61840, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839, 61839]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With