1

I am trying to populate with an array with a given number of elements(this parameter is stated in the function) given that there is a startValue and endValue for example populate myArray with 5 numbers between 5 and 15.

function populateArray(num, startValue, endValue){
var j,
    localArray=[];
for(j=startValue;j<=endValue;j+=1){
    var k = Math.floor(Math.random()* j);
    localArray.push(k);
}
console.log(localArray);
}

where num is the number of elements wanted in the array _ I don't know how to implement this. thanks in advance.

cssJumper
  • 43
  • 6

4 Answers4

0
for(j=0;j<=num;j+=1){
    var k = Math.floor(Math.random()* (endValue-startValue) + startValue);
    localArray.push(k);
}
Anton
  • 9,682
  • 11
  • 38
  • 68
0

You got it the wrong way:

Your for loop should be the amount of number that you are required, thus something like this in pseudo code.

For j while j < num increase by 1

Then to get the random number, you are also having it wrong. Math.random() returns a number between 0 and 1. Which means that you can do something like this:

space between the 2 numbers is Math.abs(endValue - startValue). The absolute isn't necessary but just in case you mix the numbers. Then you'll have to do something like this:

Multiply the random value by the space and add the startValue as an offset. Then you can use floor to remove the decimals.

Loïc Faure-Lacroix
  • 13,220
  • 6
  • 67
  • 99
0

Live Demo

function populateArray(num, startValue, endValue){
    var j,
        localArray=[];
    for(j=0; j <= num; j++){
        var k = randomIntFromInterval(startValue, endValue);
        localArray.push(k);
    }
    return localArray; 
}

//From: http://stackoverflow.com/a/7228322/402706
function randomIntFromInterval(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

console.log(populateArray(10, 8, 12));
Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
0

One possible approach:

function createRandomArray(length, minValue, maxValue) {
  // assert(minValue <= maxValue)
  // assert(length >= 0)

  var arr = [];
  var multiplier = maxValue - minValue + 1;

  while (length--) {
    arr.push(minValue + Math.floor(Math.random() * multiplier));
  }

  return arr;
}

// and that's how it can be used in your case:
var randArr = createRandomArray(5, 5, 15);

In your solution, you somehow ended up using range start and end numbers to define the size of resulting array (in for loop).

Two sidenotes here. First, when you need to execute the loop strictly N times, for loop can be replaced with while (n--) one. I often use the latter to differentiate these N-times cases.

Second, when dealing with ranges, there's often a confusion about inclusiveness of their end (and sometimes start) values. min and max name prefixes are far more clear in this aspect.

raina77ow
  • 103,633
  • 15
  • 192
  • 229