Page 1 of 1

Create unique id using recursion

Posted: Tue Oct 14, 2008 9:08 am
by papa
Hi,

I'm stuck on a function I've been trying to do a neat solution for but haven't got the skills apparently.

Looping through an array and see if matches my rand(id). If match, use the same function again and if running out of question or find unique question, end it.

Code: Select all

<?php
 
function randQuestion($questions, $answeredQ) {
    reset($answeredQ);
    $limit = count($questions);
    $q = rand(0, $limit);
        foreach($answeredQ as $answered) {
            if($q == $answered) {
                $question .= "$q vs $answered - match<br />";
                randQuestion($questions, $answeredQ);
            } else $question .= "$q vs $answered<br />";
        }
        return $question;
}
 
echo randQuestion(array("q1", "q2", "q3", "q4", "q5"), array(0, 1, 2, 3));
 
?>
The $question var is just for error coding.
Thanks.

Re: Create unique id using recursion

Posted: Tue Oct 14, 2008 9:32 am
by onion2k
What are you trying to achieve? I can't see the point of your function.

Re: Create unique id using recursion

Posted: Tue Oct 14, 2008 9:39 am
by papa
Pick a random question out of the question array, and if that question is already in answeredQ array. Pick another random question.

Might have overdone the whole thing.

Re: Create unique id using recursion

Posted: Tue Oct 14, 2008 9:50 am
by VladSun
Order the questions by random() and then use successive incrementing index to pick up another question ;)

Re: Create unique id using recursion

Posted: Tue Oct 14, 2008 10:22 am
by papa
Hah, thanks man!