简体   繁体   中英

Getting n random elements from array and creating duplicates when there's not enough elements

I have arrays of objects, ex:

let array1 = [
{name: '1', image: '1.jpg'},
{name: '2', image: '2.jpg'},
{name: '3', image: '4.jpg'},
{name: '4', image: '5.jpg'},
];

I want to get n random element of it and found function that serves this purpose:

function getRandom(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);
 while (n--) {
        var x = Math.floor(Math.random() * len);
        result[n] = arr[x in taken ? taken[x] : x];
        taken[x] = --len in taken ? taken[len] : len;
    }
return result
}

The only problem is that when I want to have n > arr.length this does not work. I'd like to figure out how to increase number of elements in this case. For example repeating elements that are already in it.

I tried adding conditional:

if(n > len) {
    arr.push(arr);
    console.log(arr);
}

But it does me no good since, the elements are pushed as an another object, and not separately, check the console.log:

0: {name: "1", image: "1.jpg"}
1: {name: "2", image: "2.jpg"}
2: {name: "3", image: "4.jpg"}
3: {name: "4", image: "5.jpg"}
4: Array(5)
0: {name: "1", image: "1.jpg"}
1: {name: "2", image: "2.jpg"}
2: {name: "3", image: "4.jpg"}
3: {name: "4", image: "5.jpg"}
4: (5) [{…}, {…}, {…}, {…}, Array(5)]
length: 5

None of other things I tried doesn't work. If someone could figure out the way around it I would really appreciate it.

//////// edit - whole function getRandom (arr, n):

function getRandom(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);
    if (n > len)
       throw new RangeError("getRandom: more elements taken than available");
    while (n--) {
        var x = Math.floor(Math.random() * len);
        result[n] = arr[x in taken ? taken[x] : x];
        taken[x] = --len in taken ? taken[len] : len;
    }

    if (arr == warmUpAll) {
      document.getElementById("warmup").innerHTML = '<span class="exerciseheader">Warm Up - 10 minutes</span>' + "</br>" ;
    }
    else if (arr == legsAll){
      document.getElementById("legsDisplay").innerHTML = '<span class="exerciseheader">Legs</span>' + "</br>";
    }

    for (let i=0;i<result.length;i+=1) {
      let displayname = document.createTextNode(result[i].name);
      if (arr == warmUpAll) {
        source = './images/warmUp/' + result[i].image;
        warmUpSources.push(source);
        document.getElementById('warmup').appendChild(displayname);
        document.getElementById('warmup').appendChild(document.createElement("br" ));
      }
      else if (arr == armsAll) {
        source = './images/arms/' + result[i].image;
        armsSources.push(source);
        document.getElementById('armsDisplay').appendChild(displayname);
        document.getElementById('armsDisplay').appendChild(document.createElement("br" ));
      }
  }
}

Currently your code gives syntax error of extra bracket and removing the bracket it works but returns only 1 random value. Its clearly lacking a loop. you can try this

function fillArrayRandomly(array, n) {
let res = [];
while (res.length !== n) {
    let randomValue = array[Math.floor(Math.random() * array.length)];
    res.push(randomValue);
}
return res;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM