Reputation: 33
I have searched through the internet but I haven't find any straightforward answer. What I am trying to develop is basically a three same-object matching game. I have 3 UIButtons in one row. (each of these 3 buttons have a black hat icon).There are gonna be 3 unique types of hats. There are 3 rows of three items each. I want to touch the first hat and reveal a number from 0 to 2 (Let's say 1). After choosing the first hat, I want the second hat to generate a number between the 2 remained numbers( the choices are 0 and 2, let's say 2). And finally when I touch the third hat, it will generate the last remainder (number 0 in this example).The main reason for picking the numbers is because I want a certain number to represent a unique "Hat", so when I pick a hat with the number 1, a blue hat will pop out, with the number 0 a red hat etc... I have implemented the whole animation and stuff. I am just struggling in the "Unique random number picking". I am sure arrays will be a part of the "Random logic" but I haven't managed to implement it correctly... Any help would be HIGHLY appreciated :) Thank you all!
Upvotes: 2
Views: 2452
Reputation: 3718
You can write a method that does this really simply with arc4random and a mutable array property that stores the numbers that have been shown as NSNumber objects.
-(NSInteger) randomNumberZeroToTwo {
NSInteger randomNumber = (NSInteger) arc4random_uniform(3); // picks between 0 and n-1 where n is 3 in this case, so it will return a result between 0 and 2
if ([self.mutableArrayContainingNumbers containsObject: [NSNumber numberWithInteger:randomNumber]])
[self randomNumberZeroToTwo] // call the method again and get a new object
} else {
// end case, it doesn't contain it so you have a number you can use
[self.mutableArrayContainingNumbers addObject: [NSNumber numberWithInteger:randomNumber]];
return randomNumber;
}
}
arc4random returns an NSUInteger so you have to cast it to avoid warnings with NSNumber.
Also make sure to instantiate your mutable array by adding this code so it does so automatically when self.mutableArrayContainingNumbers is called (i.e. lazy instantiation).
-(NSMutableArray *) mutableArrayContainingNumbers
{
if (!_mutableArrayContainingNumbers)
_mutableArrayContainingNumbers = [[NSMutableArray alloc] init];
return _mutableArrayContainingNumbers;
}
Upvotes: 3
Reputation: 1724
Have an array of pickable numbers.
pickable = @[0,1,2]; //Use NSNumbers but you get the idea.
/*Code to generate random number (rNum) with the range of 0-([pickable count]-1)*/
/*
Assign the number to your hat
and then remove that object from pickable
*/
[pickable removeObjectAtIndex:rNum]
and loop over that until [pickable count] == 0;
I hope that gives you a start good luck.
Upvotes: 1