I’ve declared a static array of integer from 1 to 5 and now want to call randomly each number with each press of a button. I don’t want the same number to be called twice.
int randomNumber;
static int size = 5;
int position = arc4random() % size - 1;
randomNumber = usedNumbers[position];
int switcher = usedNumbers[size]; // wrong
usedNumbers[position] = usedNumbers[size];
size--;
usedNumbers[position] = switcher;
Here’s what I’ve done so far. There’s a hole in my logic somewhere and I could do with some help. I think it’s something to do with the switcher which is trying to hold a number whilst another is being deleted.
If all you want to do is to show a random number every time the button is clicked, here is some code that can help.
But first, the line you use to create the position is wrong. Do this instead:
Second, I’d suggest to use an
NSArrayorNSMutableArrayto hold your data.I assume that you have a method that is called when you press a button. Inside that method you can simply put something like this:
So.. If you add the array as an instance variable to your class, your header file would look something like this:
And your implementation file:
If you do it like this, a random number will be chosen from the array every time the button is clicked.
Also, remember to
releaseall your objects if you don’t have ARC enabled.PS: There are several other questions here on SO covering this subject. Remember to search before asking.
Update:
To make sure every number is used only once, you can remove it from your array when it is chosen. So the
buttonWasClicked:method will be something like this: