Max
Max

Reputation: 1195

Randomly access keys from dictionary

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.

Upvotes: 0

Views: 506

Answers (3)

dan_fides
dan_fides

Reputation: 324

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];

Upvotes: 3

thedayofcondor
thedayofcondor

Reputation: 3876

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

Upvotes: 2

Zack Brown
Zack Brown

Reputation: 6028

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.

Upvotes: 0

Related Questions