0

I have a dictionary of objects that I would like to access in a random order. It doesn't have to be properly random but just have a good amount of variation.

The dictionary looks something like this like this:

'customer0' : '<Customer Object>'
'customer1' : 'inactive'
'customer2' : 'inactive'
'customer3' : 'inactive'
'customer4' : '<Customer Object>'

The key corresponds to a UI element that will be used to represent a customer in a game and basically I want them to not appear in the same order everytime.

Max
  • 1,175
  • 3
  • 12
  • 22

3 Answers3

3

About random numbers read more here on stack. So if you have string keys, you can use smth like this:

NSString *key = [NSString stringWithFormat:@"customer%d", arc4random()%5];
<customer object> *customObj = [yourDictionary objectForKey:key];
Community
  • 1
  • 1
dan_fides
  • 324
  • 1
  • 10
  • Cheers. I combined this with a while loop to randomly select the inactive customers. – Max Oct 23 '12 at 10:37
2

In pseudocode:

  1. Create a copy of the structure - you can get the keys into an array
  2. Pick a random integer n from 0 to the size of the copy -1
  3. Extract (as in retrieve and delete) the element at position n
  4. Repeat from 2) until size == 0
thedayofcondor
  • 3,860
  • 1
  • 19
  • 28
0

I haven't tested this, but something along these lines should achieve what you're aiming for:

//create dictionary
NSDictionary *dictionary = [NSDictionary dictionary];

//gather set of keys from array of keys
NSSet *keys = [NSSet setWithArray:[dictionary allKeys]];

//gather random key
NSString *key = [keys anyObject];

//gather dictionary value with key
NSString *value = [dictionary objectForKey:key];

By creating an NSSet from the NSArray of dictionary keys, you can use anyObject to gather an random key from the array.

There are surely other ways to achieve this but this is the most concise approach I can think of.

Zack Brown
  • 5,990
  • 2
  • 41
  • 54
  • Granted, `NSSet` is unordered, but `anyObject` won't return a random object from the set! – JustSid Oct 23 '12 at 10:27
  • Agreed. But this approach seemed cleaner than using arc4random. The NSSet documentation states: `The object returned is chosen at the set’s convenience—the selection is not guaranteed to be random.` – Zack Brown Oct 23 '12 at 10:37