Objective-C: How to find the most common string in an array?

后端 未结 3 1537
礼貌的吻别
礼貌的吻别 2021-01-21 08:02

I have an array of strings from an online database that I trying to determine the most commonly used word. The values inside the arrays will vary but I want to check the most co

3条回答
  •  死守一世寂寞
    2021-01-21 08:20

    You can use the word as a key into a dictionary.

    NSMutableDictionary *words = [NSMutableDictionary dictionary];
    for (NSString *word in stringArray) {
        if (!words[word]) {
            [words setValue:[NSDecimalNumber zero] forKey:word];
        }
    
        words[word] = [words[word] decimalNumberByAdding:[NSDecimalNumber one]];
    }
    

    Now iterate through words and find the key with the highest value.

    NSString *mostCommon;
    NSDecimalNumber *curMax = [NSDecimalNumber zero];
    for (NSString *key in [words allKeys]) {
        if ([words[key] compare:curMax] == NSOrderedDescending) {
            mostCommon = key;
            curMax = word[key];
        }
    }
    
    NSLog(@"Most Common Word: %@", mostCommon);
    

    EDIT: Rather than looping through the array once then looping separately through the sorted dictionary, I think we can do better and do it all in a single loop.

    NSString *mostCommon;
    NSDecimalNumber *curMax = [NSDecimalNumber zero];
    NSMutableDictionary *words = [NSMutableDictionary dictionary];
    for (NSString *word in stringArray) {
        if (!words[word]) {
            [words setValue:[NSDecimalNumber zero] forKey:word];
        }
    
        words[word] = [words[word] decimalNumberByAdding:[NSDecimalNumber one]];
    
        if ([words[word] compare:curMax] == NSOrderedDescending) {
            mostCommon = word;
            curMax = words[word];
        }
    }
    
    NSLog(@"Most Common Word: %@", mostCommon);
    

    This should be significantly faster than my answer pre-edit, though I don't know how it compares to using the NSCountedSet answer.

提交回复
热议问题