【发布时间】:2014-04-15 06:44:44
【问题描述】:
刚接触objective-c,需要帮助解决这个问题:
编写一个带有两个参数的函数:
1 表示文本文档的字符串和
2 一个整数,提供要返回的项目数。实现该函数,使其返回按词频排序的字符串列表,首先出现最频繁的词。使用您的最佳判断来决定如何分隔单词。您的解决方案应该在 O(n) 时间内运行,其中 n 是文档中的字符数。像对生产/商业系统一样实现此功能。您可以使用任何标准数据结构。
到目前为止我尝试了什么(正在进行中):` // 函数正在进行中
// -(NSString *) wordFrequency:(int)itemsToReturn inDocument:(NSString *)textDocument ;
// Get the desktop directory (where the text document is)
NSURL *desktopDirectory = [[NSFileManager defaultManager] URLForDirectory:NSDesktopDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
// Create full path to the file
NSURL *fullPath = [desktopDirectory URLByAppendingPathComponent:@"document.txt"];
// Load the string
NSString *content = [NSString stringWithContentsOfURL:fullPath encoding:NSUTF8StringEncoding error:nil];
// Optional code for confirmation - Check that the file is here and print its content to the console
// NSLog(@" The string is:%@", content);
// Create an array with the words contain in the string
NSArray *myWords = [content componentsSeparatedByString:@" "];
// Optional code for confirmation - Print content of the array to the console
// NSLog(@"array: %@", myWords);
// Take an NSCountedSet of objects in an array and order those objects by their object count then returns a sorted array, sorted in descending order by the count of the objects.
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:myWords];
NSMutableArray *dictArray = [NSMutableArray array];
[countedSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
[dictArray addObject:@{@"word": obj,
@"count": @([countedSet countForObject:obj])}];
}];
NSLog(@"Words sorted by count: %@", [dictArray sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"count" ascending:NO]]]);
}
return 0;
}
【问题讨论】:
-
您的问题是什么?你的算法有效吗?如果没有,你会得到什么结果? - 如果您的问题是关于改进工作代码,那么最好在codereview.stackexchange.com提问。
-
嗨 Martin,我希望有人能帮助我解决这个编码挑战,因为我被困在了 Objective-c 的新手。我在其他讨论中看到了 ruby 中相同问题的编码示例,但我希望一些人在 Objective-c 中看到一些代码示例,以便更好地理解并让我走上正确的道路。
-
算法工作我得到类似的东西:2014-04-15 02:59:51.387 [6666:303] 按计数排序的单词:( { count = 6; word = and; }, { count = 5; word = a; }, { count = 5; word = the; }, { count = 3; word = of; 但我不知道如何将此代码集成到适当的函数中
标签: objective-c algorithm sorting big-o