21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

char *p = buf;<br />

while (--len)<br />

*p++ = (char)spc_rand_range(33, 126);<br />

*p = 0;<br />

return buf;<br />

}<br />

11.15 Shuffling Fairly<br />

<strong>Problem</strong><br />

You have an ordered list of items that you would like to shuffle randomly, then visit<br />

one at a time. You would like to do so securely and without biasing any element.<br />

Solution<br />

For each index, swap the item at that index with the item at a random index that has<br />

not been fully processed, including the current index.<br />

Discussion<br />

Performing a statistically fair shuffle is actually not easy to do right. Many developers<br />

who implement a shuffle that seems right to them off the top of their heads get it<br />

wrong.<br />

We present code to shuffle an array of integers here. We perform a statistically fair<br />

shuffle, using the spc_rand_range( ) function from Recipe 11.11.<br />

#include <br />

void spc_shuffle(int *items, size_t numitems) {<br />

int tmp;<br />

size_t swapwith;<br />

while (--numitems) {<br />

/* Remember, it must be possible for a value to swap with itself */<br />

swapwith = spc_rand_range(0, numitems);<br />

tmp = items[swapwith];<br />

items[swapwith] = items[numitems];<br />

items[numitems] = tmp;<br />

}<br />

}<br />

If you need to shuffle an array of objects, you can use this function to first permute<br />

an array of integers, then use that permutation to reorder the elements in your array.<br />

That is, if you have three database records, and you shuffle the list [1, 2, 3], getting<br />

[3, 1, 2], you would build a new array consisting of the records in the listed order.<br />

612 | Chapter 11: Random Numbers<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!