简体   繁体   中英

Pick random elements from an array without repeating

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

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

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