为什么这段代码没有产生正确的输出? [英] Why doesn't this code produce the correct output?
本文介绍了为什么这段代码没有产生正确的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个字符串和一个数字,此函数将生成该字符串中所有可能的n个字母的组合。
Given a string and a number, this function will produce all possible combinations of n letters from that string.
如果我传递abcd和3,那么我应该得到以下输出:
i.e. If I pass "abcd" and 3, then I should get the following output:
abc
abd
acd
bcd
这是代码
- (void)viewDidLoad {
[super viewDidLoad];
[self expand_combinations:@"abcd" arg2:@"" arg3:3];
}
-(void) expand_combinations: (NSString *) remaining_string arg2:(NSString *)s arg3:(int) remain_depth
{
if(remain_depth==0)
{
printf("%s\n",[s UTF8String]);
return;
}
for(int k=0; k < [remaining_string length]; ++k)
{
s = [s stringByAppendingString:[[remaining_string substringFromIndex:k] substringToIndex:1]];
[self expand_combinations:[remaining_string substringFromIndex:k+1] arg2:s arg3:remain_depth - 1];
}
return;
}
而是这是打印输出
abc
abcd
abcd
abcd
推荐答案
只是一个快速而脏的解决方案(没有重命名变量名等)
Just a quick and dirty solution (didn't rename variable names and so on) for your function
-(void) expand_combinations: (NSString *) remaining_string arg2:(NSString *)s arg3:(int) remain_depth
{
NSString *newString = [remaining_string stringByReplacingCharactersInRange:NSMakeRange(remain_depth, 1) withString:@""];
// NSLog(newString);
if(remain_depth==0)
{
printf("%s\n",[s UTF8String]);
return;
}
[self expand_combinations:remaining_string arg2:s arg3:remain_depth - 1];
return;
}
输出(我使用NSLog)
Output (I used NSLog)
2010-09-26 04:27:26.462 Untitled[5417:207] abc
2010-09-26 04:27:26.462 Untitled[5417:207] abd
2010-09-26 04:27:26.463 Untitled[5417:207] acd
2010-09-26 04:27:26.467 Untitled[5417:207] bcd
这篇关于为什么这段代码没有产生正确的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文