cocoa touch:rand()返回相同的字符串

Mat*_* S. 1 iphone random cocoa-touch rubiks-cube

这是我的代码:

-(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];
}
Run Code Online (Sandbox Code Playgroud)

每次我运行它都会得到完全相同的字符串"D'BB'DL'D'F'L'B'U'DDD'L'URBFD'B'"

我想要它做的是每次运行它时给我一个新的移动设置

我已经运行了至少30次,以确保它不是侥幸,并且它确实返回相同的字符串,果然,确实如此.

Joh*_*ker 5

您需要确保首先为随机数生成器播种.

在进入你的循环之前做:

srand(time(NULL));
Run Code Online (Sandbox Code Playgroud)