Pick random elements from an array without repeating

我与影子孤独终老i 提交于 2019-12-04 06:34:10

问题


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



来源:https://stackoverflow.com/questions/28473095/pick-random-elements-from-an-array-without-repeating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!