Is this C implementation of Fisher-Yates shuffle correct? -


There is a single implementation of Fisher-Yets that I want to use in a deck-shifting routine. Am I doing it correctly (n = length of the array)?

Note: To make a makeup-loop for modulo bias (see) it adds up the process slightly upwards and eliminating it if you do not care about low-bit prejudices. It is possible. J, TMP, Upper_bound; Srand (time (zero)); For (i = n - 1; i> gt; i--) {upper_bound = RAND_MAX - ((RAND_MAX% (i + 1)) + 1); Do {j = rand (%)% (i + 1); } While (h & gt; upper_bound); Tmp = array [ja]; Array [j] = array [i]; Array [ii] = tmp; First of all, you should remove the code to generate a random number, which is Be distributed evenly between a 0 (inclusive) and n (exclusive) for a separate function. It's a good job of the job you need elsewhere.

Second, I do not call the srand inside the shuffle function, depending on the random number generator the caller will start this way A deck can shuffle more than once in the bar.

Third, you have to go to j & gt; Before dividing by i + 1 , upper_bound is not possible that i is ever with RAND_MAX .

  Fixed int rand_int (int n) {int limit = RAND_MAX - RAND_MAX% n; Int rnd; Do {rnd = rand (); } While (RD & gt; = range); Return rnd% n; } Zero resize (int * array, int n) {int i, j, tmp; For (i = n - 1; i> i;) {j = rand_int (i + 1); Tmp = array [ja]; Array [j] = array [i]; Array [ii] = tmp; }}  

To verify that this implementation may be correct, you need to make sure that you have created the random number generator with the log2 (n!) In other words, the n s to the rand_int function given the product to n! should be .


Comments

Popular posts from this blog

c# - sqlDecimal to decimal clr stored procedure Unable to cast object of type 'System.Data.SqlTypes.SqlDecimal' to type 'System.IConvertible' -

Calling GetGUIThreadInfo from Outlook VBA -

Obfuscating Python code? -