如何随机化JavaScript数组并确保顺序项不一样

时间:2013-02-01 14:43:09

标签: javascript shuffle

我有一系列问题,其中一些问题可能是相同的。

 {"choice":"attributes","text":"Happy"},
 {"choice":"attributes","text":"Fun"}, 
 {"choice":"attributes","text":"Enjoyable"},   
 {"choice":"attributes","text":"Pleasurable"},  
 {"choice":"attributes","text":"Ecstatic"},
 {"choice":"attributes","text":"Sad"},   
 {"choice":"attributes","text":"Tedious"},
 {"choice":"attributes","text":"Annoying"},  
 {"choice":"attributes","text":"Depressing"},
 {"choice":"attributes","text":"Unhappy"},
 {"choice":"attributes","text":"Happy"},
 {"choice":"attributes","text":"Fun"},
 {"choice":"attributes","text":"Enjoyable"},

目前我正在使用FisherYatesShuffle随机化数组()我真正需要做的是在洗牌后查看列表并确保没有两个连续项是相同的,任何想法?

e.g。我们永远不会得到

{"choice":"attributes","text":"Happy"},
{"choice":"attributes","text":"Happy"},

编辑以澄清一些问题。 必须保留数组中的所有项。

1 个答案:

答案 0 :(得分:2)

继续对阵列进行洗牌,直到没有两个相同的顺序项为止:

var shuffled = false,
    i = 0,
    length = myArray.length,
    previous;
while(!shuffled){                            // repeat this until we have a shuffled array.
    myArray = FisherYatesShuffle(myArray);   // (Assuming you have that function)
    shuffled = true;                         // first, assume the array is shuffled,
    for(i = 0; i < length && shuffled; i++){ // Then loop through the array to check if it is indeed shuffled.
        if(previous && previous.text == myArray[i].text){
            shuffled = false;                // If it isn't shuffled, set shuffled to false.
        }                                    // This breaks the for loop, and tries to shuffle the array again.
        previous = myArray[i];
    }
}

优点是它只会洗牌一次,如果循环证明第一次被充分洗牌,但是如果有很多项是相同的,它可以经常迭代循环,因为它必须随机返回来自FisherYatesShuffle的正确改组的数组。