Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have to find a way to combine the two sets of random numbers (the first and second random <code>{0,1,2,3,4}</code> ) and make <code>n*n</code> distinct possibilities. Basically the problem is that with addition you get something like this</p> <pre><code> X 0 1 2 3 4 0 0 1 2 3 4 Y 1 1 2 3 4 5 2 2 3 4 5 6 3 3 4 5 6 7 4 4 5 6 7 8 </code></pre> <p>Which has duplicates, which is not what you want. One possible way to combine the two sets would be the <code>Z = X + Y*5</code> where <code>X</code> and <code>Y</code> are the two random numbers. That would give you a set of results like this</p> <pre><code> X 0 1 2 3 4 0 0 1 2 3 4 Y 1 5 6 7 8 9 2 10 11 12 13 14 3 15 16 17 18 19 4 20 21 22 23 24 </code></pre> <p>So now that you have a bigger set of random numbers, you need to do the reverse and make it smaller. This set has <code>25</code> distinct values (because you started with 5, and used two random numbers, so <code>5*5=25</code>). The set you want has 8 distinct values. A naïve way to do this would be</p> <pre><code>x = rnd(5) // {0,1,2,3,4} y = rnd(5) // {0,1,2,3,4} z = x+y*5 // {0-24} random07 = x mod 8 </code></pre> <p>This would indeed have a range of <code>{0,7}</code>. But the values <code>{1,7}</code> would appear 3/25 times, and the value <code>0</code> would appear 4/25 times. This is because <code>0 mod 8 = 0</code>, <code>8 mod 8 = 0</code>, <code>16 mod 8 = 0</code> and <em><code>24 mod 8 = 0</code></em>.</p> <p>To fix this, you can modify the code above to this.</p> <pre><code>do { x = rnd(5) // {0,1,2,3,4} y = rnd(5) // {0,1,2,3,4} z = x+y*5 // {0-24} while (z != 24) random07 = z mod 8 </code></pre> <p>This will take the one value (<code>24</code>) that is throwing off your probabilities and discard it. Generating a new random number if you get a 'bad' value like this will make your algorithm run very slightly longer (in this case 1/25 of the time it will take 2x as long to run, 1/625 it will take 3x as long, etc). But it will give you the right probabilities.</p>
 

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