Get random element from array, display it, and loop - but never followed by the same element

后端 未结 3 1177
一生所求
一生所求 2021-01-24 08:48

I wrote a simple enough randomize function that loops through the elements in an array and displays them one after the other.

See it here.

function chang         


        
3条回答
  •  清歌不尽
    2021-01-24 09:14

    To give an even chance of all elements except the previous one being used do the following:

    var i, j, n = 10;
    setInterval(function () {
      // Subtract 1 from n since we are actually selecting from a smaller set
      j = Math.floor(Math.random() * (n-1)); 
      // if the number we just generated is equal to or greater than the previous
      // number then add one to move up past it
      if (j >= i) j += 1;
      document.write(j + ' ');
      i = j;
    }, 1000);
    

    The comments in the code should explain how this works. The key thing to remember is that you are actually selecting from 9 possible values, not from 10.

    You should initialize i to be a random element in the array before starting.

    For a simple walk through on a 3 element array with the second element selected:

    i=1, n=3

    The random result gives us either 0 or 1.

    If it is 0 then j >= i returns false and we select element zero

    If it is 1 then j >= i returns true and we select the third element.

    You can do the same walk through with i being 0 and and i being 2 to see that it never overruns the buffer and always has an equal chance to select all other elements.

    You can then extend that same logic to an array of any size. It works exactly the same way.

提交回复
热议问题