在这里,我使用以下代码来重新排列NSMuttable数组,同时洗牌数组只重复一个值并且所有数据都正常工作,我应该做什么改变而不重复洗牌?
words = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3",@"4", nil] ;
NSUInteger count = [words count];
for (int i = 0; i < count; i++)
{
NSInteger nElements = count - i;
NSInteger n = (arc4random() % nElements) + i;
NSLog(@"n val %d i val %d",i,n);
[words exchangeObjectAtIndex:i withObjectAtIndex:n];
}
NSlog输出
2012-12-31 12:49:05.730 quizer[1607:c07] n val 0 i val 0
2012-12-31 12:49:05.731 quizer[1607:c07] n val 1 i val 3
2012-12-31 12:49:05.731 quizer[1607:c07] n val 2 i val 2
2012-12-31 12:49:05.732 quizer[1607:c07] n val 3 i val 3
请帮我解决
答案 0 :(得分:1)
此代码可以为您提供帮助,
shuffle数组只包含介于0到TOTAL_NUMBER(您的数组大小)之间的每个数字。
您可以从中随机播放现有阵列。
@synthesize alreadyGeneratedNumbers;//this is a mutableArray.
int TOTAL_NUMBER=5;//size of array
-(int)generateRandomNumber{
int low_bound = 0;
int high_bound = TOTAL_NUMBER;
int width = high_bound - low_bound;
int randomNumber = low_bound + arc4random() % width;
return randomNumber;
}
-(IBAction)randomNumbers:(UIButton *)sender
{
NSMutableArray *startArray=[NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
NSMutableArray *shuffle = [NSMutableArray new];
BOOL contains=YES;
while ([shuffle count]<5) {
NSNumber *generatedNumber=[NSNumber numberWithInt:[self generateRandomNumber]];
//NSLog(@"->%@",generatedNumber);
if (![alreadyGeneratedNumbers containsObject:generatedNumber]) {
[shuffle addObject:generatedNumber];
contains=NO;
[alreadyGeneratedNumbers addObject:generatedNumber];
}
}
if ([alreadyGeneratedNumbers count] >= TOTAL_NUMBER) {
NSLog(@"\nOne shuffel ended.....what to reshuffle");
[alreadyGeneratedNumbers removeAllObjects];
}
NSMutableArray *shuffledArray=[NSMutableArray new];
for (NSNumber *index in shuffle) {
[shuffledArray addObject:[startArray objectAtIndex:[index integerValue]]];
}
NSLog(@"Shuffled array = %@",shuffledArray);
}
答案 1 :(得分:0)
要删除NSMutableArray
,
// Removing duplicate entry from array
NSArray *copy = [words copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator])
{
if ([words indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound)
{
[words removeObjectAtIndex:index];
}
index--;
}
[copy release];
您可以在每次添加对象时进行检查。