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() を使用して配列をランダム化していますが、シャッフル後にリストを調べて、連続する 2 つの項目が同じでないことを確認する必要があります。

例:私たちは決して得ません

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

編集していくつかの質問を解決してください。配列内のすべての項目を保持する必要があります。

4

1 に答える 1

2

同じ連続する項目が 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];
    }
}

利点は、ループが最初に十分にシャッフルされることが証明された場合、1 回だけシャッフルされることですが、同じアイテムが多数ある場合は、適切にシャッフルされたアイテムをランダムに返す必要があるため、ループを頻繁に反復できます。からの配列FisherYatesShuffle

于 2013-02-01T14:50:02.297 に答える