views:

63

answers:

2

The following code works perfectly and shows the correct output:

- (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;
    }

    NSString *str = [[NSString alloc] initWithString:s];
    for(int k=0; k < [remaining_string length]; ++k)
    {

        str = [s stringByAppendingString:[[remaining_string substringFromIndex:k] substringToIndex:1]];
        [self expand_combinations:[remaining_string substringFromIndex:k+1] arg2:str arg3:remain_depth - 1];

    }
    return;
}

However, instead of outputting the results, I want to return them to an NSArray. How can this code be changed to do that? I need to use the information that this function generates in other parts of my program.

+2  A: 

basicaly you have:
create mutable array in viewDidLoad before [self expand_combinations ...
add aditional parameter (mutable array) to expand_combinations
populate array in expand_combinations

GameBit
+3  A: 

There are several things that you need to change in your code.

  • First - consider changing the name of your method to something more legible and meaningful than -expand_combinations:arg2:arg3.
  • Second - you have a memory leak. You don't need to set allocate memory and initialize str with the string s, because you change its value right away in the loop without releasing the old value.
  • Third - take a look at NSMutableArray. At the beginning of the method, create an array with [NSMutableArray array], and at every line that you have printf, instead, add the string to the array. Then return it.
itaiferber
Should I not alloc and init str, or should I just release it after the loop?
awakeFromNib
awakeFromNib: `str` is a variable. You should not allocate and init a string and assign its pointer to that variable because you assign another string's pointer to that variable immediately afterwards, both wasting and leaking the first string.
Peter Hosey