Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an Array with the numbers needed to sum a specific number [duplicate]

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.

like image 838
Óscar Giménez Avatar asked Mar 04 '23 18:03

Óscar Giménez


2 Answers

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.

like image 127
Aritra Chakraborty Avatar answered Mar 10 '23 03:03

Aritra Chakraborty


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.

  • Calculate an "even" portion of targetVal.
  • Push that portion to the result array.
  • Substract that portion from targetValue.
  • Repeat until length is 0

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]
like image 21
cronide Avatar answered Mar 10 '23 02:03

cronide