0

I have an array like this:

var arr = [0,1,2,3,4,5]

What I need is to write a function, which will generate a new array of random length (but less or equal than arr.length) and won't generate repeated numbers. Something like:

var arrNew = [2,4,0]

but not

var arrNew = [2,4,2,2,0]

I came up with this, but it generates repeated elements:

var list = [0,1,2,3,4,5];

var getRandomNumberRange = function (min, max) {
  return Math.floor(Math.random() * (max - min) + min);
};

var getRandomArr = function (list) {
  var arr = new Array(getRandomNumberRange(1, 6));
  for (var i = 0; i < arr.length; i++) {
    arr[i] = list[getRandomNumber(list.length)];
  }
  return arr;
};

Appreciate your help!

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • 1
    Does this answer your question? [Generate unique random numbers between 1 and 100](https://stackoverflow.com/questions/2380019/generate-unique-random-numbers-between-1-and-100) – Nick Parsons Jul 24 '20 at 08:17
  • Where is getRandomNumber function ? – Pritesh Jul 24 '20 at 08:20

3 Answers3

1

NOTE: there's nothing stopping this code from giving you an empty array as your random array.

var arr = [0,1,2,3,4,5, 36, 15, 25]

function generateRandomArrayFromSeed(arr) {
  // Create a new set to keep track of what values we've used
  const used = new Set();
  // generate a new array.
  const newArr = [];
  // what random length will we be using today?
  const newLength = getRandomNumber(arr.length);
  // while our new array is still less than our newly randomized length, we run this block of code
  while(newArr.length < newLength) {
    // first, we generate a random index
    const randomNumber = getRandomNumber(arr.length);
    // then we check if the value at this index is in our set; if it is, we continue to the next iteration of the loop, and none of the remaining code is ran.
    if(used.has(arr[randomNumber])) continue;
    // otherwise, push this new value to our array
    newArr.push(arr[randomNumber]);
    // and update our used set by adding our random number
    used.add(arr[randomNumber]);
  }
  // finally return this new random array.
  return newArr;
}

function getRandomNumber(limit = 10) {
  return Math.floor(Math.random() * limit);
}

console.log(generateRandomArrayFromSeed(arr));
Jhecht
  • 4,407
  • 1
  • 26
  • 44
0

Moving the data vrom an array datastructure to a Set could solve the problem.
Sets dont accept duplicate values.
For more on Set in javascript, see MDN here

To convert the Set back to an array, use Array.from()

0

To avoid duplicates in you final array just use Set and convert it back to an array using Array.from

Save you result inside set as below:

arr = Array.from(new Set(<result array>));
Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
Pritesh
  • 337
  • 1
  • 10