Home > Software engineering >  Divide a number into equal values and push to an array
Divide a number into equal values and push to an array

Time:06-10

I need to divide a number equally and push the values on the array. I'm using 100 as an example, but when I do it, it goes [28, 24, 24, 24], and I need it to be [25, 25, 25, 25]

const divide = () => {
  var number = 100
  var n = 4

  var values = []
  while(number > 0 && n > 0){
    var a = Math.floor(number / n / 4) * 4
    number -= a
    n--
    values.push(a)
  }

  console.log(values)
}

CodePudding user response:

You have couple of issues in your code, decreasing the n means that the next loop the divided value will change.

Here is an updated version that works correctly:

    const divide = (number = 100, n = 4) => {
      const values = [];
      let times = n;
      while(times > 0){
        values.push(Math.floor(number / n));
        times--;
      }
      return values;
    }
    
    console.log(divide());

To explain how this should work, in order to get the same number in the arrays nth times, n should not be changed. So we are copying its value to a local variable that is hten used to create / control the loop. Each time the loop runs we divide the target number with n - for all of the iterations so we get the same number and its always 1/4 of the 100. Hope this helps ..

CodePudding user response:

If I understand your question correctly:

const divide = (num = 100, n = 4) => new Array(n).fill(num / n);

CodePudding user response:

The Math.floor() function returns the largest integer less than or equal to a given number, in your code this functions make the result incorrect

this is a correct code :

const divide = () => {
  var number = 100
  var n = 4

  var values = []
  for(int i=1;i<=4;i  ){
    values.push(a/4)
  }

  console.log(values)
}
  • Related