Word Frequency Algorithm in Objective C

Word Frequency Algorithm in Objective C

Created By: Debasis Das (21-Aug-2015)

In this post we will create two sample code/ approach for deriving the word count, word frequency of each word in a input string.

Word Frequency Algorithm in Objective C – Approach 1

-(void)wordFrequencyAlgorithm1{
    NSString *initialSentence = @"Dominick Dom Cobb (Leonardo DiCaprio) and Arthur (Joseph Gordon-Levitt) are extractors, people who perform corporate espionage using an experimental military technology to infiltrate the subconscious of their targets and extract information while experiencing shared dreaming. Their latest target is Japanese businessman Saito (Ken Watanabe). The extraction from Saito fails when sabotaged by a memory of Cobb's deceased wife Mal (Marion Cotillard). Saito reveals that he was actually auditioning the team to perform the difficult act of inception  planting an idea in a person's subconscious. In order to break up the energy conglomerate of ailing competitor Maurice Fischer (Pete Postlethwaite), Saito wants Cobb to plant into the mind of Fischer's son and heir, Robert (Cillian Murphy), the idea of dissolving his father's company. Should Cobb succeed, Saito tells Cobb he will use his influence to clear Cobb of a murder charge, which will allow Cobb to return home to his children. Although Arthur claims that inception is impossible as it is always possible to trace the origin of an idea, Cobb, claiming past experience, accepts the offer and sets about assembling his team: Eames (Tom Hardy), a conman and identity forger; Yusuf (Dileep Rao), a chemist who concocts a powerful sedative for a stable dream within a dream strategy; Ariadne (Ellen Page), an architecture student tasked with designing the labyrinth of the dream landscapes, recruited with the help of Professor Stephen Miles (Michael Caine). Saito insists on accompanying the team to verify their success. When Ariadne shares a dream with Cobb, he reveals to her that his subconscious recreates Mal, and she appears frequently in his dreams as a hostile force. ";

    NSMutableString *sentence = [[NSMutableString alloc] initWithString:initialSentence];
    
[sentence replaceOccurrencesOfString:@"," withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@")" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@"(" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@"." withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@":" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@";" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@"'" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];

//There are more effective ways of achieving the above. Removal of special characters from an input string    
    NSArray * keys = [sentence componentsSeparatedByString:@" "];
    NSArray *uniqueKeys = [[NSSet setWithArray:keys ] allObjects]; //We are using this to remove duplicate entries from the array and create a new array with only unique values

    NSMutableDictionary *wordFrequencyDictionary = [NSMutableDictionary new];
    
    for (NSString *key in uniqueKeys){
        [wordFrequencyDictionary setObject:@1 forKey:key]; //Here we are initializing a dictionary with each word with a count of 1
    }
    
    for (NSString *word in keys){
        [wordFrequencyDictionary setObject:@([[wordFrequencyDictionary objectForKey:word] intValue] + 1) forKey:word];
    }

    NSLog(@"wordFrequencyDictionary %@",wordFrequencyDictionary);
    
}

Word Frequency Algorithm in Objective C – Approach 2

-(void)wordFrequencyAlgorithm2{
    NSString *initialSentence = @"Dominick Dom Cobb (Leonardo DiCaprio) and Arthur (Joseph Gordon-Levitt) are extractors, people who perform corporate espionage using an experimental military technology to infiltrate the subconscious of their targets and extract information while experiencing shared dreaming. Their latest target is Japanese businessman Saito (Ken Watanabe). The extraction from Saito fails when sabotaged by a memory of Cobb's deceased wife Mal (Marion Cotillard). Saito reveals that he was actually auditioning the team to perform the difficult act of inception  planting an idea in a person's subconscious. In order to break up the energy conglomerate of ailing competitor Maurice Fischer (Pete Postlethwaite), Saito wants Cobb to plant into the mind of Fischer's son and heir, Robert (Cillian Murphy), the idea of dissolving his father's company. Should Cobb succeed, Saito tells Cobb he will use his influence to clear Cobb of a murder charge, which will allow Cobb to return home to his children. Although Arthur claims that inception is impossible as it is always possible to trace the origin of an idea, Cobb, claiming past experience, accepts the offer and sets about assembling his team: Eames (Tom Hardy), a conman and identity forger; Yusuf (Dileep Rao), a chemist who concocts a powerful sedative for a stable dream within a dream strategy; Ariadne (Ellen Page), an architecture student tasked with designing the labyrinth of the dream landscapes, recruited with the help of Professor Stephen Miles (Michael Caine). Saito insists on accompanying the team to verify their success. When Ariadne shares a dream with Cobb, he reveals to her that his subconscious recreates Mal, and she appears frequently in his dreams as a hostile force. ";
    
    NSMutableString *sentence = [[NSMutableString alloc] initWithString:initialSentence];
    [sentence replaceOccurrencesOfString:@"," withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@")" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@"(" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@"." withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@":" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@";" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    [sentence replaceOccurrencesOfString:@"'" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sentence.length)];
    
    NSArray * keys = [sentence componentsSeparatedByString:@" "];
    NSArray *sortedArray = [keys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    
    NSLog(@"sortedArray %@",sortedArray);
    
    int count = 1;
    
    NSMutableDictionary *wordFrequencyDictionary = [NSMutableDictionary new];
    
    for (int i =0; i < sortedArray.count; i++){
        if (((i+1) < sortedArray.count) && ([[sortedArray objectAtIndex:i+1] isEqualToString:[sortedArray objectAtIndex:i]]))
        {
            count = count+1;
            [wordFrequencyDictionary setObject:[NSNumber numberWithInt:count] forKey:[sortedArray objectAtIndex:i]];
        }
        else
        {
            count = 1;
        }
    }
    NSLog(@"wordFrequencyDictionary %@",wordFrequencyDictionary);
    
}
Posted in algorithms, Cocoa, Objective C Tagged with: , , , ,
0 comments on “Word Frequency Algorithm in Objective C
1 Pings/Trackbacks for "Word Frequency Algorithm in Objective C"
  1. […] The logic for generating the hashmap/NSDictionary for the tag cloud can be found here Word Frequency Algorithms in Objective C […]

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news