iphone Development - adding a loop?
i need help create a loop that check if the item selected in the array is already picked before, if yes randomize it again. implement in this function:
-(NSString*) randomBallPick:(NSString*) Filename
{
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
for (int c=0;c&开发者_如何转开发lt;37;c++)
{
NSString *imageName = [NSString stringWithFormat:@"image_%d.png", c];
[imageArray addObject: imageName];
}
int numFileNames = [imageArray count];
int chosen = arc4random() % numFileNames;
Filename = [imageArray objectAtIndex: chosen];
return Filename;
[imageArray release];
}
I answered your other question about this function: Here's the answer from there modified to only return file names that haven't been returned yet:
- (NSString*)randomBallPick
{
static NSMutableArray *imageArray;
if (!imageArray) {
imageArray = [[NSMutableArray alloc] init];
for (int c = 0; c < 37; c++)
{
NSString *imageName = [NSString stringWithFormat:@"ball_%d.png", c];
[imageArray addObject:imageName];
}
}
//pick one filename
NSUInteger numFileNames = [imageArray count];
if (numFileNames < 1) {
return nil; // or handle this case in some other way
}
NSUInteger chosen = arc4random() % numFileNames;
NSString *chosenFilename = [imageArray objectAtIndex:chosen];
[imageArray removeObjectAtIndex:chosen];
return chosenFilename;
}
Basically, when it returns one of the file names, it also removes it from imageArray
.
Of course, once imageArray
is empty (numFileNames < 1
) the above returns nil
. Not sure if that's appropriate and you might need to handle that case differently.
You'll need somewhere to store whether a particular ball has already been selected.
Once you pick a ball, if it's been selected before, go back to the start of the function and try again.
Note that this probably isn't the best way to handle it - once you get down to where there are only a handful of not-yet-picked balls in the array, you'll spend a lot of time re-picking until you get a new one. A better way would be to maintain a list of not-yet-picked balls, and splice them out of the list as they get picked.
EDIT: psuedocode version of the loop-until-we've-found-it method. You'll need to implement getIt() and Foo::hasNotBeenPickedYet(), as well as translate it into actual code.
Foo foo = null;
while(!foo) {
Foo temp = getIt();
if(temp.hasNotBeenPickedYet())
foo = temp;
}
return foo;
精彩评论