Filip Filip - 3 months ago 5x
Objective-C Question

Calculating value of K without messages


Find the value of K in

without any messages/calls

I was given this hint:

The numbers in the array will never exceed 1-9.

NSArray *myInterViewArray = @[@2,@1,@3,@9,@9,@8,@7];


If you send 3, the array will return the 3 biggest values in
myInterViewArray * 3
. So in the example below, K = 9 + 9 + 8.


I was asked this question a while back in an interview and was completely stumped. The first solution that I could think of looked something like this:

Interview Test Array:

[self findingK:myInterViewArray abc:3];

-(int)findingK:(NSArray *)myArray abc:(int)k{ // With Reverse Object Enumerator
myArray = [[[myArray sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];

int tempA = 0;

for (int i = 0; i < k; i++) {
tempA += [[myArray objectAtIndex:i] intValue];

k = tempA;
return k;

But apparently that was a big no-no. They wanted me to find the value of K without using any messages. That means that I was unable to use
and even

Now to the point!

I've been thinking about this for quite a while and I still can't think of an approach without messages. Does anyone have any ideas?


There is only one way to do that and that is bridging the array to CF type and then use plain C, e.g.:

NSArray *array = @[@1, @2, @3];
CFArrayRef cfArray = (__bridge CFArrayRef)(array);

NSLog(@"%@", CFArrayGetValueAtIndex(cfArray, 0));

However, if the value is a NSNumber, you will still need messages to access its numeric value.

Most likely the authors of the question didn't have a very good knowledge of the concept of messages. Maybe they thought that subscripting and property access were not messages or something else.

Using objects in Obj-C without messages is impossible. Every property access, every method call, every method initialization is done using messages.

Rereading the question, they probably wanted you to implement the algorithm without using library functions, e.g. sort (e.g. you could implement a K-heap and use that heap to find the K highest numbers in a for iteration).