Created
February 2, 2014 14:35
-
-
Save hebertialmeida/8769297 to your computer and use it in GitHub Desktop.
Finding the most common character in a string
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
- (NSString *)mostCommonCharacter:(NSString *)string | |
{ | |
__block NSMutableArray *charIndex = [[NSMutableArray alloc] init]; | |
// Enumerate | |
[string enumerateSubstringsInRange:NSMakeRange(0, string.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) | |
{ | |
[charIndex addObject:substring]; | |
}]; | |
// Count | |
NSCountedSet *counter = [[NSCountedSet alloc] initWithArray:charIndex]; | |
NSString *mostCommon; | |
NSUInteger highest = 0; | |
for (NSString *s in counter) { | |
if ([counter countForObject:s] > highest) { | |
highest = [counter countForObject:s]; | |
mostCommon = s; | |
} | |
} | |
return mostCommon; | |
} | |
// Demo | |
- (void)viewDidLoad | |
{ | |
NSLog(@"mostCommon: %@", [self mostCommonCharacter:@"aaaabbbaaaa * bbbccccccccdd ddddddd dddd"]); | |
// this returns -> d | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment