Last active
December 25, 2015 22:39
-
-
Save tLewisII/7051441 to your computer and use it in GitHub Desktop.
Recursion in Objective-C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (BOOL)isPowerOfTwo:(NSUInteger)number { | |
if(number == 0) return NO; | |
if(number == 1 || number == 2) return YES; | |
return [self findPower:number accumulator:2]; | |
} | |
- (BOOL)findPower:(NSUInteger)n accumulator:(NSUInteger)accumulator { | |
if(accumulator == n) return YES; | |
if(accumulator > n) return NO; | |
return [self findPower:n accumulator:(2 * accumulator)]; | |
} | |
- (NSUInteger)lengthOfArraysSuffix:(NSArray *)one two:(NSArray *)two { | |
return [self lengthOfArraysSuffix:one two:two accumulator:0 equal:YES]; | |
} | |
- (NSUInteger)lengthOfArraysSuffix:(NSArray *)one two:(NSArray *)two accumulator:(NSUInteger)acc equal:(BOOL)equal { | |
if(one.count == 0 || two.count == 0 || !equal) return acc; | |
id object1 = [one lastObject]; | |
id object2 = [two lastObject]; | |
BOOL isEqual = [object1 compare:object2] == NSOrderedSame; | |
NSArray *subArrayOne = [one subarrayWithRange:NSMakeRange(0, one.count - 1)]; | |
NSArray *subArrayTwo = [two subarrayWithRange:NSMakeRange(0, two.count - 1)]; | |
NSUInteger newAccumulator = isEqual ? acc + 1 : acc + 0; | |
return [self lengthOfArraysSuffix:subArrayOne two:subArrayTwo accumulator:newAccumulator equal:isEqual]; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment