TransWikia.com

Create a functions, which creates a new array out of an existing one, which has less or equal amount of elements and no repeats

Stack Overflow Asked by Vitaliy Avdyeyev on December 25, 2021

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!

3 Answers

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));

Answered by Jhecht on December 25, 2021

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>));

Answered by Pritesh on December 25, 2021

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()

Answered by user10691667 on December 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP