Snippet: Unknown Random Selection

Here’s a nifty little snippet found in this iphonesdk thread for selecting randomly from among an unknown number of objects in an array. Rather than build some sort of collection of the objects/indices/whatever that satisfy your test and then randomizing, combine the selection with the test!

NSObject *result = nil;
int candidateCount = 0;
for (NSObject *test in arrayOfObjects)
if ([test isACandidate])
if ([utilRandom: ++candidateCount] == 0)
result = test;

where utilRandom:num returns { 0 .. num – 1 }. When done, candidateCount is number of objects that matched your test query and result has a 1/candidateCount chance of being each of them. Nice little low-overhead convenience we could’ve used a number of times, that.

0 Responses to “Snippet: Unknown Random Selection”

  1. No Comments

Leave a Reply