tags:

views:

40

answers:

1

i am trying to have an array that contains 5 integers(0,1,2,3,4) called questionNumber the questionNumber is supposed to end up with 4 so therefore i am trying to make a function to call randomly numbers 0-3 and go from one to another (add 1 to prevoius number) until they reach 4. How would this be implemented? many thanks

A: 

Well you can use arc4random() % x; to get a random number from 0 to x-1. So you want a random number between 0-3 so use arc4random() % 4;

Then store this random value in an int and use that to increment.

for instance

int currentNum = -1;

[self incrementNum];

void incrementNum() {

if (currentNum == -1)
    currentNum = [self getRandomNumber];
else if (currentNum < 5)
    currentNum++;

}

int getRandomNumber() {

return arc4random() % 4;

}

EDIT::

From reading what you have said above i think i missunderstood. Do you want that array to be randomly sorted so the 4 questions could come out of the array in order such as: 2,4,1,3

If so then you want something like:

//QuestionArray[] contains the questions from 0-4 // NewQuestionArray[] will contain the new randomly ordered questions // If first loop then that question won't have appeared before // If on i >= 1 then loop through previous numbers to see if that question has appeared, if it has store it then increment i int i = 0;

while (i < 5) {

 int newNum = [self getRandomNumber];
 if (i == 0)
 {
    NewQuestionArray[i] = QuestionArray[newNum];
    i++;
 }
 else
 {
    BOOL repeatNum = FALSE;
    for (int p = 0; p < i; p++)
    {
        if (newNum == NewQuestionArray[i])
        {
             repeatNum = TRUE;
        }
    }
    if (!repeatNum)
    {
       NewQuestionArray[i] = QuestionArray[newNum];
       i++;
    }
 }

}

Code might not be great but should give you an understanding. I haven't explained the code as i haven't really included anything in there that isn't basic. But i can explain it better if you want me to.

i am getting the following error when I try using the last edit you supplied. It states "invalid operands to binary ==" so im not sure what to use now?
Alx
well i guess you would want if (QuestionArray[newNum] == NewQuestionArray[i])
Well this depends what type your QuestionArray[] is using. If it contains a string then i guess you would want: if ([[QuestionArray objectAtIndex:newNum] isEqualTo:[NewQuestionArray objectAtIndex:i]])