Using JavaScript Random in Different ways

JavaScript Math.random() is a Math function that returns a random floating-point number between [0, 1) that is, including 0 but excluding 1. In this tutorial, we will see the different ways in which we can use JavaScript Math.random() for different applications.

Before diving into the tutorial, let us recall some of the basic random function applications.

  • Displaying a random number between the given range

    To display a random number between the given range, including minimum range but excluding maximum, the following code snippet can be used.

    function random_range(low, high){
       return Math.floor(low + Math.random()*(high-low))
    }
    

    Low and high are the ranges and it is assumed to be integers and not floating values.

  • Displaying a random number between the given range, Inclusive

    The following code snippet is used to display a random number between a given range where both min and max range is inclusive.

    function random_range(low, high){
       return Math.floor(low + Math.random()*(high-low+1))
    }
    

    Here also, low and high ranges are assumed to be integers.

These are the basic random function applications. For more information, please refer to the official documentation.

Now let’s move on to our tutorial.

Generating an Array of Random Numbers between 0 (inclusive) and 1 (exclusive) in JavaScript

We can generate an n-dimensional array filled with random numbers in the range [0, 1). We will see how to generate them for 1-D and 2-D arrays.

  • 1-D Array of Random numbers

This is a simple straightforward implementation. The function random1DArray takes size as an argument. Initially, we create an empty array. Then we iterate through the loop for size times and each time, we create a random number and push it to the array. Finally, we return the array.

function random1DArray(size){
  random_arr = [];
  for( i=0; i<size; i++){
    random_arr.push(Math.random());
  }
  return random_arr;
}

console.log(random1DArray(5));

Output

[0.0952778139642434, 0.9189917848729967, 0.2605812184376721, 0.0032629562265031886, 0.6504691713009889]

 

  • 2-D Array of Random numbers

This is another simple straightforward implementation. The function random2DArray takes the number of rows and columns as the argument. Initially, we create an empty array. Then we iterate through the loop for row times and for each iteration we run into another loop for column times and push a random number into the corresponding row and column of that array. Finally, we return the array.

function random2DArray(row, col){
  random_arr = [];
  for( i=0; i<row; i++){
    random_arr[i] = [];
    for( j=0; j<col; j++){
      random_arr[i].push(Math.random());
    }
  }
  return random_arr;
}

console.log(random2DArray(2,3));

Output

[[0.5488288891993967, 0.0298192985486605, 0.11928803737803206],
[0.3147064790737486, 0.029036556122976176, 0.6606564516524003]]

 

Generating an Array of Random Numbers between Min and Max range

In the above application, we generated numbers between [0, 1). Here we will do the same for a given minimum (inclusive) and maximum (inclusive) ranges. Here, we will use the function random_range() function which is explained at the beginning of the article, to return a random integer between the two given ranges.

  • 1-D Array of Random numbers

The function random1DArray takes 3 arguments namely size, min, and max. An empty array is created and it is looped through size times. Each time random_range function is called passing, min and max value to it. It then returns a random integer between the given range and the returned value is pushed into the array. Finally, the array is returned.

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

function random1DArray(size, min, max){ 
  random_arr = []; 
  for( i=0; i<size; i++){ 
    random_arr.push(random_range(min, max)); 
    }
    return random_arr;
}

console.log(random1DArray(size = 3, min = 2, max = 5));

Output

[5, 2, 3]

 

  • 2-D Array of Random numbers

This function, random2DArray takes 4 arguments – row, col, min, max. We iterate through the loop for row times and then column times and we call the random_range function to return a random integer. We push it to the array and return the array finally.

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

function random2DArray(row, col, min, max){
  random_arr = [];
  for( i=0; i<row; i++){
    random_arr[i] = [];
    for( j=0; j<col; j++){
      random_arr[i].push(random_range(min, max));
    }
  }
  return random_arr;
}

console.log(random2DArray(row = 2, col = 3, min = 5, max = 10));

Output

[[8, 7, 6], [7, 5, 8]]

 

Generate a Random Array of size n from another Array

Using Javascript Math.random(), we can generate an array whose elements are derived randomly from another array. We can think of this scenario in 2 ways, that is, generating the array with replacement and generating the array without replacement.

  • Generate Array with Replacement

Here, we can choose the elements from another array, any number of times. The function randomArray gets 2 arguments – arr which is the array and size which is the length array to be formed. We create an empty array and a loop to run for size times.  In each iteration, we call another function random_range which we discussed earlier. We pass length the of arr as an argument and a random integer between 0 and length of arr –1 is returned, and stored in a variable called index. Then in the arr array, the element present at the index position is pushed into the new array. Finally, the newly formed array is returned.

function random_range(max){ 
  min = 0;
  return Math.floor(min + Math.random()*(max-min)) 
}

function randomArray(arr, size){
  random_arr = [];
  for( i=0; i<size; i++){
    index = random_range(arr.length)
    random_arr.push(arr[index]);
  }
  return random_arr;
}

console.log(randomArray([2, 5, 0, 7, 6, 4], 4));

Output

[6, 0, 6, 7]

 

  • Generate Array without Replacement

This works almost the same as the above code except there is no replacement. It means once an element is chosen from the other array, it cannot be chosen again. The function randomArray takes 2 arguments – arr which is the array and size which is the length of the array to be formed. Initially, we check whether the length of arr is greater than or equal to size. If not, we cannot generate the array and print the appropriate message. Else we create an empty array and a loop to run for size times. We follow the same steps which we discussed for ‘with replacement’ except we remove the randomly chosen element from the original array. It can be done using splice() function of Javascript. This is to ensure that there will be no replacement. Finally, the newly formed array is returned.

function random_range(max){ 
  min = 0;
  return Math.floor(min + Math.random()*(max-min)) 
}

function randomArray(arr, size){
  
  if(size > arr.length){
    console.log('Cannot Generate Array.');
    return;
  }
  random_arr = [];
  for( i=0; i<size; i++){
    random_number = arr[random_range(arr.length)]
    random_arr.push(random_number);
    index = arr.indexOf(random_number);
    arr.splice(index, 1);
  }
  return random_arr;
}

arr = [1, 2, 3, 5, 6]
console.log(randomArray(arr, 3))

Output

[[8, 7, 6], [7, 5, 8]]

Please post your comments, doubts, queries in the comment box. Happy Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *