可可触摸:rand() 返回相同的字符串
这是我的代码:
-(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];
}
每次运行它时,我都会得到完全相同的字符串“D'B B'D L'D'F'L'B'U'DD D'L'URBF D'B'”
我想要它做什么每次运行它时都会给我一个新的移动集,
我已经运行了至少 30 次,以确保它不是侥幸,并且它确实返回了相同的字符串,而且确实如此。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要确保首先为随机数生成器播种。
在进入循环之前执行以下操作:
you need to make sure you seed your random number generator first.
before entering your loop do:
请注意,您创建了两次
finalMoves
。一次使用[[NSMutableString alloc] init]
,然后再次使用[NSMutableString stringWithCapacity:0]
。这意味着您正在泄漏内存。像这样清理这段代码怎么样:
假设你会经常调用它,那么将可能的移动保留在全局中是有意义的(因为 Objective-C 缺乏类变量)
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:
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)