Fawad Ghafoor
Fawad Ghafoor

Reputation: 6207

random question in game

i am working in a game that can display a random question to user ,all work is going well,but the problem is that there is a probability that a same user can get the same question at same session,i dont want it, here is my code

$runs     = $_REQUEST['runs'];
$query    = "SELECT max(id) FROM question$runs";
$result1  = db_execute($query);
$ans      = mysql_fetch_array($result1);
$max      = $ans['0'];
$rand_no  = mt_rand(0,$max);
$query1   = "SELECT * FROM question$runs WHERE id='$rand_no'";

now how can i avoid the same question from a same user at same session any idea?plz share thanQ all

Upvotes: 1

Views: 639

Answers (5)

Fawad Ghafoor
Fawad Ghafoor

Reputation: 6207

i think there is no need of session here.

function avoid_random_repeat($r)
     $rand           = mt_rand(0,$max);
     $unique         = avoid_random_repeat($rand);

   if(in_array($r,$testing)){
      $rand_no  = mt_rand(0,$max);
      avoid_random_repeat($rand_no);
      }
     else{
   array_push($testing,$r);
     return;
      }
  }

Upvotes: 0

tenfour
tenfour

Reputation: 36896

If memory is an issue and you cannot store every question answered by every active session, you could just store a single random seed with each session, and the # of questions answered. For each question answered, use a shuffle algorithm (i.e. random permutation) and return the next item in the sequence.

[update]

Another option is... IF you don't mind everyone having the same order of questions, then just assign a random number to each question and return them in sequence, ordered by the random number.

Upvotes: 0

Dave Child
Dave Child

Reputation: 7881

As Voooza said, store asked questions in the session. Something like this should do the trick:

session_start();
$runs     = $_REQUEST['runs'];
$query    = "SELECT max(id) FROM question$runs";
$result1  = db_execute($query);
$ans      = mysql_fetch_array($result1);
$max      = $ans['0'];
$valid_question = false;
while (!$valid_question) {
    $rand_no = mt_rand(0,$max);
    if (!in_array($rand_no, $_SESSION['questions'])) {
        $valid_question = true;
    }
}
$_SESSION['questions'][] = $rand_no;
$query1   = "SELECT * FROM question$runs WHERE id='$rand_no'";

Upvotes: 3

Voooza
Voooza

Reputation: 779

create an array with previous question ids and store it into $_SESSION. When generating new random number check if its already there. If so regenerate random number

Upvotes: 3

duffymo
duffymo

Reputation: 308763

Have a data structure that contains the questions asked during a particular question. Add new questions to that container every time you create one; check the container each time to make sure that the new question doesn't appear. If it does, look for another one.

Upvotes: 1

Related Questions