views:

243

answers:

2

Here's my code:

-(void)randommoves
{

NSArray *possiblemoves =[NSArray arrayWithObjects:@"R ",@"R' ",@"L ",@"L' ",@"B ",@"B' ",@"F ",@"F' ",@"U ",@"U' ",@"D ",@"D' ", nil];
NSMutableString *finalmoves = [[NSMutableString alloc] init];
finalmoves = [NSMutableString stringWithCapacity:0]; 
[finalmoves retain];
int i = 0;
for (i=0; i<20; i++) {
    int r = rand() % 13;
    NSString *string = [possiblemoves objectAtIndex:r];
    [finalmoves appendString:string];
}
NSLog(@"%@",finalmoves);
[finalmoves release];
}

And every time I run it I get the EXACT same string "D' B B' D L' D' F' L' B' U' D D D' L' U R B F D' B' "

What I want it to do is give me a new move set every time I run it

I've ran this at least 30 times to make sure that it wasn't a fluke, and that it really WAS returning the same string, and sure enough, it is.

+3  A: 

you need to make sure you seed your random number generator first.

before entering your loop do:

srand(time(NULL));
John Boker
thanks, it worked (and also uncovered a little bug I had in int r = rand() % 13; where I forgot to count for 0)
Matt S.
+1  A: 

Note that you are creating finalMoves twice. Once with [[NSMutableString alloc] init] and then again with [NSMutableString stringWithCapacity:0]. This means you are leaking memory.

How about cleaning up this code like this:

static NSArray* sPossibleMoves = nil;

+ (void) initialize
{
    sPossibleMoves = [[NSArray arrayWithObjects: @"R ",@"R' ",@"L ",@"L' ",@"B ",@"B' ",@"F ",
        @"F' ",@"U ",@"U' ",@"D ",@"D' ", nil] retain];
}

- (void) randomMoves
{
    NSMutableString* finalmoves = [NSMutableString stringWithCapacity: 20];
    if (finalMoves != nil) {
        for (int i = 0; i < 20; i++) {
            [finalMoves appendString: [sPossibleMoves objectAtIndex:
                (rand() % [sPossibleMoves count])]];
        }
        NSLog(@"%@",finalmoves);
    }
}

Assuming that you will call this often, it makes sense to keep the possible moves around in a global (because Objective-C lacks class variables)

St3fan
thanks a bunch! I just had to add the srand(time(NULL)); to it and it worked! That's much better then what I was going to do (believe me, that code that I posted above would never make it into the shipping application)
Matt S.