P
P
Pesetsu2020-03-13 04:56:22
JavaScript
Pesetsu, 2020-03-13 04:56:22

Divide a number into parts but no more than x at a time?

There is a certain integer - 70, you need to split it into parts so that each part of the number is not more than 15, it can be less
How to do this using JavaScript?
What is needed in the end? Get an array with the number of received parts and their size. Something like:
[8, 15, 15, 12, ...].length // 4

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Araik, 2020-03-13
@Pesetsu

As an option, you can:

var a = 70;
var b = 15;
var result= [];

num = (a - (a % b)) / b;

for (i=0; i < num; i++) {
  result.push(b);
}

if ((a % b) < b && (a % b) != 0) {
  result.push((a % b));
}

console.log(result);  // (5) [15, 15, 15, 15, 10]

With random numbers:
var a = 70;
var min = 5;
var max = 15;
var result = [];

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; 
}

while (a > 0) {
  b = getRandomIntInclusive(min, max);
  a = a - b;

  if (a >= 0 ) {
    result.push(b);
  } 

  if (a < 0) {
    b = b + a;

    if (b < min) {
      _t = min - b;
      b = b + _t;

      result.forEach(function(item, i) {
          if ((item - _t) > min) {
            result[i] = item - _t;          
            _t = 0; 
          }
        });
    }              
    result.push(b);
  }
}

var result_sum = result.reduce(function(sum, current) {
  return sum + current;
}, 0);


console.log('Сумма всех чисел: '+result_sum); // 70
console.log(result); // (7) [15, 6, 10, 7, 5, 15, 12]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question