开发者

picking items from array that contains integers

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开发者_C百科 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜