Created
April 15, 2013 14:18
-
-
Save ichaos/5388410 to your computer and use it in GitHub Desktop.
How to choose a item from a list randomly ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//only iterator the list once, but call the random function n times. | |
int count = 0; | |
Node *head = list_head(); | |
int value; | |
for (p = head; p; p = p->next) { | |
if (random() % ++count == 0) { | |
value = p->data; | |
} | |
} | |
return value; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment