lundi 7 mars 2016

Make sure that the first element after the shuffle in JavaScript is not the same as the last element in the previous shuffle

This fiddle demonstrates my problem: http://ift.tt/1ns1KBG

I would like to make sure that every time a user clicks a button a random element from the array will be displayed. The problem is that sometimes when the new shuffle is carried out, the first element in the newly shuffled array is the same as the last element in the previously shuffled array. On these occasions when the user clicks the button the same element is displayed. The user has to then click the button again (or more times) to display a different element. I would like to avoid this.

I've tried introducing the if statement to shuffle again if the first element is equal to the last element but this does not seem to work.

Your help would be greatly appreciated.

The HTML code:

    <div id="container">
        <button id="clickHere">Click here to pick a random element from the array</button>
        <div id="resultDiv"></div>
    </div><!-- container -->

The JavaScript code:

/* define the array with a list of elements */
var arrayList = [
"1st element in array</br>",
"2nd element in array</br>",
"3rd element in array</br>",
];

/* define the function to shuffle the array */
function shuffleArray() {
for (var i = arrayList.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = arrayList[i];
    arrayList[i] = arrayList[j];
    arrayList[j] = temp;
}
}

/* execute the shuffleArray function */
shuffleArray();

/* button event initiating the randomiser function */
document.getElementById('clickHere').onclick = function () {
    randomiser ();
}

/* populate the resultDiv for the first time */
document.getElementById('resultDiv').innerHTML = arrayList[0];

/* define the array index value for the first click */
var arrayIndex = 1;

/* define the main function */
function randomiser () {
    document.getElementById('resultDiv').innerHTML = arrayList[arrayIndex];
    arrayIndex = (arrayIndex+1);
    if (arrayIndex>arrayList.length-1) {
        arrayIndex = 0;
        var lastArrayElement = arrayList[arrayList.length-1]
        shuffleArray();
        var firstArrayElement = arrayList[0];
        if (firstArrayElement == lastArrayElement) {
            shuffleArray();
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire