0

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

 {"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() 对数组进行随机化,但我真正需要做的是在随机播放列表后确保没有两个连续的项目是相同的,知道吗?

例如,我们永远不会得到

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

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

4

1 回答 1

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.

于 2013-02-01T14:50:02.297 回答