Pick random elements from an array without repeati

2020-05-03 13:31发布

问题:

I'm displaying random numbers on individual sprites and want to shuffle the individual container with the same no displaying on it. how to shuffle a set of sprites randomly without repeating the same color?

My array is:

   var color = new Array();
   color[0] = 'greenBox';
   color[1] = 'blueBox';
   color[2] = 'purpleBox';
   color[3] = 'yellowBox';
   color[4] = 'redBox';
   color[5] = 'whiteBox';
   color[6] = 'pinkBox';

回答1:

If you don't need the array later, you could do something like this:

var color = [
    "greenBox",
    "blueBox",
    ...
];

while (color.length != 0) {
    var index = Math.floor(Math.random()*color.length);
    var pickedColor = color[index];
    colors.splice(index, 1);  // This removes the picked element from the array
    doStuffWith(pickedColor);
}

This will destroy the array, but it will never pick the same element twice