问题
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.
回答1:
you need to make sure you seed your random number generator first.
before entering your loop do:
srand(time(NULL));
回答2:
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)
来源:https://stackoverflow.com/questions/2215737/cocoa-touch-rand-returning-the-same-string