Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>The code generate a random <a href="http://en.wikipedia.org/wiki/Permutation" rel="nofollow noreferrer">permutation</a> of the original array.</strong></p> <p>However, note that this is biased - it does not generate all permutations in uniform distribution. <a href="https://stackoverflow.com/questions/5131341/what-distribution-do-you-get-from-this-broken-random-shuffle">This thread</a> discusses what is the affect of this bias.</p> <p>To overcome this issue - you might want to have a look on <strong><a href="http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle" rel="nofollow noreferrer">fisher yates shuffle</a></strong> (which main difference is, to generate a random number in range [i,n) in each iteration instead of in range [0,n).)</p> <hr> <p><strong>EDIT:</strong> <br>You might better understand it if you encapsulate the assignments in a method:</p> <pre><code>private static void swap(int[] array, int i, int j) { tempNum = array[j]; array[j] = array[i]; array[i]=tempNum; } </code></pre> <p>Now, the code will be simpler to follow:</p> <pre><code>for(int i = 0; i&lt; leftbut.length; i++) { //choose a random index in the array int randomNumber =(int)(Math.random()*leftbut.length); //swap the element in index i with the random element chosen in the array swap(leftbut, i, randomNumber); } </code></pre> <p>The idea is you <code>swap()</code> each element in the array with a random index. This random index is chosen randomly from the array, and its index is denoted as <code>randomNumber</code>. <br>Since you only <code>swap()</code> items around, you can easily prove that the output array is a permutation of the original.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload