Saturday, 7 September 2013

Objective-C implementation of Ruby "chunk"

Objective-C implementation of Ruby "chunk"

I have an Objective-C application where I'm trying to sort an NSArray
while grouping the array elements that are equal. Ideally, I would
generate a new array of sets, where each set in the new array contains one
or more of the original array elements and all of the elements in each set
are equal. It would work similarly to the Ruby "chunk" method
To give an example, imagine I had an NSArray containing NSNumbers
equivalent to the following:
[1, 3, 5, 7, 9, 8, 5, 3, 2, 4, 3, 6]
I would want the new array to contain 9 sets that look like:
[ (1), (2), (3, 3, 3), (4), (5, 5), (6), (7), (8), (9) ]
In Ruby I would be able to first sort the array and then chunk it to get
what I want. I'm trying to come up with a reasonably efficient way to do
it in Objective-C.
I could set up a dictionary containing each possible value as a key with
an NSSet as the value for each key. I could then loop through the initial
array, finding the appropriate key and updating its set as I go. I could
finally sort the contents of that dictionary to get a list of sorted sets.
I could do all that, but it seems like there should be a better way that
I'm missing. Also, the values I'm sorting by could actually be
floating-point values, so using them as keys in a dictionary is likely to
be of limited value.
Can anyone think of a more clever way of doing this? Am I missing
something obvious here?

No comments:

Post a Comment