Skip to content

Instantly share code, notes, and snippets.

@AlexGladkov
Created March 6, 2016 17:51
Show Gist options
  • Save AlexGladkov/a08f625ddaa437cb415c to your computer and use it in GitHub Desktop.
Save AlexGladkov/a08f625ddaa437cb415c to your computer and use it in GitHub Desktop.
#import "ASCIICounter.h"
static const int kASCIISymbolsCount = 256;
char* fillMappingArrayInSequence(char* str, int size, char* asciiMappingArray) {
for (int currentSymbolPosition = 0; currentSymbolPosition < size; currentSymbolPosition++) {
asciiMappingArray[str[currentSymbolPosition]]++;
}
return asciiMappingArray;
}
char mostFrequentCharacterFromMappingArray(char *array) {
int maxCount = 0;
char maxCountPosition = 0;
for (int currentAsciiSymbol = 0; currentAsciiSymbol < kASCIISymbolsCount; currentAsciiSymbol++) {
if (array[currentAsciiSymbol] > maxCount) {
maxCount = array[currentAsciiSymbol];
maxCountPosition = currentAsciiSymbol;
}
}
return maxCountPosition;
}
char* mergeMappingArraysToFirst(char* array1, char* array2) {
for (int currentAsciiSymbol = 0; currentAsciiSymbol < kASCIISymbolsCount; currentAsciiSymbol++) {
array1[currentAsciiSymbol] = array1[currentAsciiSymbol] + array2[currentAsciiSymbol];
}
return array1;
}
char mostFrequentCharacter(char *str ,int size) {
//Делим массив пополам
int size1 = size / 2;
int size2 = size - size1;
__block char * asciiMappingArray1 = (char *)calloc(kASCIISymbolsCount, sizeof(char));
__block char * asciiMappingArray2 = (char *)calloc(kASCIISymbolsCount, sizeof(char));
//Создание параллельной очереди
dispatch_queue_t queue = dispatch_queue_create("test char", DISPATCH_QUEUE_CONCURRENT);
//Запуск счетчика по левой части строки
dispatch_async(queue, ^{
fillMappingArrayInSequence(str, size1, asciiMappingArray1);
});
//Запуск счетчика по правой части строки
dispatch_async(queue, ^{
fillMappingArrayInSequence(str + size1, size2, asciiMappingArray2);
});
//Синхронизируем и объединяем счетчики
dispatch_barrier_sync(queue, ^{mergeMappingArraysToFirst(asciiMappingArray1, asciiMappingArray2);});
char resultChar = mostFrequentCharacterFromMappingArray(asciiMappingArray1);
free(asciiMappingArray1);
free(asciiMappingArray2);
return resultChar;
}
@implementation ASCIICounter
- (char) mostFrequentCharacter:(char *)str size:(int)size {
return mostFrequentCharacter(str, size);
}
@end
ASCIICounter *counter = [[ASCIICounter alloc] init];
NSLog(@"%c", [counter mostFrequentCharacter:"abcabcfffffgggg" size:15]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment