-2

I am trying to return the lowest number in an array.

Parameter: arrayOfNumbers - An array of NSNumbers.

Return: The lowest number in the array as an NSInteger.

The code I have thus far doesn't give me any errors, but does not pass the unit tests. What am I doing wrong?

- (NSInteger) lowestNumberInArray:(NSArray *)arrayOfNumbers {

    NSNumber* smallest = [arrayOfNumbers valueForKeyPath:@"@min.self"];
    for (NSInteger i = 0; i < arrayOfNumbers.count; i++) {
        if (arrayOfNumbers[i] < smallest) {
            smallest = arrayOfNumbers[i];
        }
    }

    NSInteger smallestValue = [smallest integerValue];
    return smallestValue;

}

This is the unit test:

- (void) testThatLowestNumberIsReturned {
    NSInteger lowestNumber = [self.handler lowestNumberInArray:@[@3, @8, @-4, @0]];
    XCTAssertEqual(lowestNumber, -4, @"Lowest number should be -4.");

    lowestNumber = [self.handler lowestNumberInArray:@[@83, @124, @422, @953, @1004, @9532, @-1000]];
    XCTAssertEqual(lowestNumber, -1000, @"Lowest number should be -1000.");    
}
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
ioskaveen
  • 196
  • 1
  • 4
  • 14

2 Answers2

3

This method

NSNumber* smallest = [arrayOfNumbers valueForKeyPath:@"@min.self"];

will already determine the smallest number in the array, so the loop inside the method is superfluous (on top of being plain wrong, as @vikingosegundo notices).

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
2

you are comparing objects with c types, resulting im pointer addresses being compared with an int.

Beside the fact your smallest is already the smallest, as you used the KVC collection operator @min.self (see Glorfindel answer), the following code shows you correct comparison

if (arrayOfNumbers[i] < smallest)

should be

if ([arrayOfNumbers[i] compare:smallest] == NSOrderingAscending)

or

if ([arrayOfNumbers[i] integerValue] < [smallest integerValue])
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178