我正在开发单词益智游戏,其中给出了一个单词。根据该单词生成随机字母...为此,我应用了逻辑以下但是一些如何根据给定单词生成随机字母。
NSMutableArray * ArrOfABCD = [[NSMutableArray alloc] initWithObjects:@ “A”,@ “B”,@ “C”,@ “d”,@ “E”,@ “F”,@ “G”,@ “H”,@ “I”,@“Ĵ “@ ”K“,@ ”L“,@ ”M“,@ ”N“,@ ”O“,@ ”P“,@ ”Q“,@ ”R“,@ ”S“,@” T ” @ “U”,@ “V”,@ “W”,@ “X”,@ “Y”,@ “Z”, 零];
float x = 70; float y = 100; float width = 30; float height = 20; for(int i =0;i<32;i++) { NSUInteger randomIndex = arc4random() %(ArrOfABCD.count); UIButton *btnLetter = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [btnLetter setFrame:CGRectMake(x, y, width, height)]; [btnLetter setTitle:[NSString stringWithFormat:@"%@",ArrOfABCD[randomIndex]]
forState:UIControlStateNormal]; [self.view addSubview:btnLetter];
x = x + width + 30; if((i+1)%4==0) { x = 70; y = y + height + 20; } }
任何人都可以告诉我哪里出错了?
答案 0 :(得分:1)
You should generate the unique random number
NSMutableArray* ArrOfWords = [[NSMutableArray alloc] initWithObjects:@"Good",@"Home",@"Beauty",@"Good",nil];
NSMutableArray *ArrOfABCD = [[NSMutableArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z", nil];
NSMutableArray *arrDuplicate=[[NSMutableArray alloc]init];
float x = 70;
float y = 100;
float width = 30;
float height = 20;
NSInteger rowIndex=4;
NSString *dataString=[ArrOfWords objectAtIndex:0];
NSMutableArray *arrNumber = [[NSMutableArray alloc]init];
for (int i = 0; i < [dataString length]; i++) {
NSInteger index=arc4random_uniform(rowIndex)+rowIndex;
NSNumber *number=[NSNumber numberWithInt:index];
while ([arrDuplicate containsObject:number] ) {
NSInteger index=arc4random_uniform(rowIndex)+rowIndex;
number=[NSNumber numberWithInt:index];
}
[arrNumber addObject:number];
[arrDuplicate addObject:number];
}
[arrDuplicate removeAllObjects];
NSMutableArray *arrayChar = [NSMutableArray array];
for (int i = 0; i < [dataString length]; i++) {
[arrayChar addObject:[NSString stringWithFormat:@"%C", [dataString characterAtIndex:i]]];
}
for(int i =0;i<32;i++)
{
NSString *str=[ArrOfABCD objectAtIndex:arc4random_uniform(ArrOfABCD.count)];
if ([arrNumber containsObject:[NSNumber numberWithInt:i]] ) {
str=[arrayChar objectAtIndex:arrDuplicate.count];
[arrDuplicate addObject:str];
}
NSLog(@"%@",str);
UIButton *btnLetter = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnLetter setFrame:CGRectMake(x, y, width, height)];
[btnLetter setTitle:str forState:UIControlStateNormal];
x = x + width + 30;
if((i+1)%4==0)
{
x = 70;
y = y + height + 20;
}
}