Question

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.

Was it helpful?

Solution

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

before entering your loop do:

srand(time(NULL));

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top