Skip to content

Instantly share code, notes, and snippets.

@Evsenev
Last active October 25, 2015 03:30
Show Gist options
  • Save Evsenev/e6d767cb775c9b2b5e07 to your computer and use it in GitHub Desktop.
Save Evsenev/e6d767cb775c9b2b5e07 to your computer and use it in GitHub Desktop.
char mostFrequentCharacter(char* string, int size)
{
int threadsCount = 2;
BOOL *threadComplete = calloc(threadsCount, sizeof(BOOL));
BOOL *freqCountInThread = calloc(threadsCount, sizeof(int));
BOOL *mostFrequentCharInThread = calloc(threadsCount, sizeof(char));
int sizeForProcessing = size/threadsCount;
dispatch_queue_t queue = dispatch_queue_create("com.evsenev.mylovechar", DISPATCH_QUEUE_CONCURRENT);
for (int i = 0; i < threadsCount; i++)
{
dispatch_async(queue,
^{
int threadIndex = i;
int start = sizeForProcessing * threadIndex;
int end = sizeForProcessing * (threadIndex+1);
if(threadIndex + 1 == threadsCount)
end = end + (size % threadsCount);
NSString *key = nil;
NSMutableSet *charsSet = [[NSMutableSet alloc] init];
NSMutableDictionary *charsCount = [[NSMutableDictionary alloc]init];
int index = start;
while (index < end) {
key = [NSString stringWithFormat:@"%c",string[index]];
if(![charsSet containsObject:key])
{
[charsSet addObject:key];
[charsCount setObject:[NSNumber numberWithInt:1] forKey:key];
}
else
{
int intValue = (int)[[charsCount objectForKey:key] integerValue] + 1;
NSNumber *count = [NSNumber numberWithInt:intValue];
[charsCount setObject:count forKey:key];
}
index++;
}
int maxCountIndex = 0;
for(int i = 0; i < charsCount.allKeys.count; i++)
{
key = [charsCount.allKeys objectAtIndex:i];
NSString *maxKey = [charsCount.allKeys objectAtIndex:maxCountIndex];
if([[charsCount objectForKey:key] integerValue] > [[charsCount objectForKey:maxKey] integerValue])
maxCountIndex = i;
}
key = [charsCount.allKeys objectAtIndex:maxCountIndex];
mostFrequentCharInThread[threadIndex] = [key characterAtIndex:0];
freqCountInThread[threadIndex] = [[charsCount.allValues objectAtIndex:maxCountIndex] integerValue];;
threadComplete[threadIndex] = YES;
});
}
BOOL allComplete = NO;
while (!allComplete)
{
for(int i = 0; i < threadsCount; i++)
{
if(!threadComplete[i])
{
allComplete = NO;
break;
}
allComplete = YES;
}
}
int resultIndex = 0;
for (int i = 0; i < threadsCount ; i++) {
if(freqCountInThread[i] > freqCountInThread[resultIndex])
resultIndex = freqCountInThread[i];
}
return mostFrequentCharInThread[resultIndex];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment