Skip to content

Instantly share code, notes, and snippets.

@ichaos
Created April 15, 2013 14:18
Show Gist options
  • Save ichaos/5388410 to your computer and use it in GitHub Desktop.
Save ichaos/5388410 to your computer and use it in GitHub Desktop.
How to choose a item from a list randomly ?
//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