-1

So say i have an array:

array1 = [1, 2, 3, 4, 5, ........, 50]

And I wanted to randomize that array into a new array that has length contraints.

For example, if I wanted a random array from array1 that was only 5 numbers long, I could get:

var arrayLength = 5

randomizedArray = [6, 20, 45, 2, 13]

Is there a way to do this with Math.random?

optionalfigure
  • 269
  • 1
  • 2
  • 9

6 Answers6

0

You can map over the array and set each item to the result of Math.random() multiplied by the upper bound (rounded):

function generateRandomArray(length, RNGUpperBound){
  return new Array(length).fill().map(e => Math.round(Math.random() * RNGUpperBound))
}
console.log(generateRandomArray(5, 10));
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

You can iterate 5 times the array and random push an index using Math.random():

let array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50];

let newLength = 5,
    newArray = [];

for (let i = 0; i < 5; i ++) {
  newArray.push(array1[Math.floor(Math.random()  * (array1.length - 1))]);
}

console.log(newArray);

However, this wouldn´t avoid to push two or more times the same item. You can check first if the item was previously included using includes() method:

let array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50];

let newLength = 5,
  newArray = [];

for (let i = 0; i < 5; i++) {
  let randomElem = null;
  // Check if element is already in the array
  do {
    randomElem = array1[Math.floor(Math.random() * (array1.length - 1))];
  }while(newArray.includes(randomElem));
  
  newArray.push(randomElem);
}

console.log(newArray);
AlexSp3
  • 2,201
  • 2
  • 7
  • 24
0

As long as the range (0..60) isn't crazy large, I'd shuffle and slice. It's a good idea to have an array shuffle handy as a generally useful tool.

// from https://stackoverflow.com/a/2450976/294949
function fyShuffle(array) {
  let currentIndex = array.length,  randomIndex;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
  return array;
}

let range = 60;
let resultLength = 5;
let array1 = [ ...Array(range).keys() ]; // the OP array

fyShuffle(array1);
console.log(array1.slice(0, resultLength))
danh
  • 62,181
  • 10
  • 95
  • 136
0

everyone else has talked about the normal way to do this already. I'll just say that rando.js is really nice for this stuff.

//if you have to use an array
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50];
console.log(randoSequence(arr).map(a => a.value).slice(-5));

//or if you prefer to be kind to yourself
console.log(randoSequence(1, 50).slice(-5))
<script src="https://randojs.com/2.0.0.js"></script>
Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15
0

Here, instead of adding n values, the code should add n distinct values (if that is the need), since if n is near to array's length, there is a possibility of elements to get repeated.

Here is a simple code snippet without importing of any new node_module.

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50];
let newArrayLength = 10;
let newArray = [];

while (newArrayLength > 0) {
  const rndIndex = Math.floor(Math.random() * array.length);
  if (!newArray.includes(array[rndIndex])) {
  newArray.push(array[rndIndex]);
  newArrayLength--;
  }
}
console.log('newArray', newArray);
Parth Mansata
  • 145
  • 1
  • 7
-1

Approach 1: Shuffle the entire array, take first N elements

You can always shuffle the entire array, and then take the first 5 elements. This wastes time and memory, but this is only an issue for very large inputs or where performance is an issue.

Use any common method to shuffle an array:

function shuffle(array) {
    return array.map((value) => ({ value, sort: Math.random() }))
        .sort((a, b) => a.sort - b.sort)
        .map(({ value }) => value)
}

Then:

const arrayLength = 5;
const array1 = [1, 2, ..., 50];

const shuffled = shuffle(array1);
// take the first n elements from the shuffled array
const sample = shuffled.slice(0, arrayLength);

Approach 2: Use a library

Many libraries have already implemented something similar - what you're looking for is a random sample of N elements. For example, try lodash's sampleSize as discussed in this answer.

Mack
  • 691
  • 3
  • 7