0

I have this problem I'm not really sure how to do it. I'm having trouble figuring out how to add items to an array using a function that generates random numbers.

First I have to build a function that takes three parameters. one is the minimum random number, the other one is the maximum, the third parameter is the length of the array.

I've tried some stuff like removing the variable x setting it to an empty array.

var newArray = [generateRandomArray(10, 1, 10)]


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

var generateRandomArray = function(max, min, length) {
  var x;
  for (y = 1; y >= length; y++) {
    x = [x.push(getRandomInt(min, max))]
    console.log(x)
  }
  return x;
}

var newArray = [generateRandomArray(10, 1, 10)] returns [5, 7, 9, 6, 6, 10, 8, 10, 9, 7]

I just get []

2
  • Your current code results in a TypeError because the function is not declared in time Commented Oct 12, 2019 at 22:25
  • Possible duplicate of Create an array with random values Commented Oct 12, 2019 at 23:01

2 Answers 2

1

You were attempting to call generateRandomArray in the snippet before the function existed, and your for loop in generateRandomArray would never run as y started as 1 and you were comparing it as >= length:

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

var generateRandomArray = function(max, min, length) {
  var x = [];
  
  for (var y = 0; y < length; y++) {
    x.push(getRandomInt(min,max));
  }

  return x;
}

var newArray = generateRandomArray(10, 1, 10);
console.log(newArray);

Sign up to request clarification or add additional context in comments.

Comments

0

Comments in code to show fixes.

Also just as a side note, I would recommend switching the min and max around on one of the two functions that use them for consistency. Just a Good Practice.

//moved generateRandomArray function to beginning so it is defined before it is called
 var generateRandomArray = function(max, min, length) {
  var x = []; //initialise array
  for (y = 1; y <= length; y++) { //fix the incorrect sign so the loop works
    x.push(getRandomInt(min, max)); //fix the fact you kept overriding x and instead just push to the array
    console.log(x)
  }
  return x;
}

var newArray = [generateRandomArray(10, 1, 10)]

console.log("newArray", newArray);

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

   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.