Ping Lee
Ping Lee

Reputation: 21

How to Generate random number within specific number

I need to generate three different random numbers without repeating, Three different random numbers need to be within 10 of the answer

        for the sample IQ Question: 4,6 ,9,6,14,6,... Ans:19
        A: random numbers 
        B: random numbers
        C: random numbers
        D: random numbers
one of them is the answer

I am now using the following code but sometimes the numbers are repeated, I have tried shuffle But which one is really random cannot satisfy random numbers need to be within 10 of the answer

$ans = $row['answer'];

$a = rand (1,10);
$a1 = rand($ans-$a   ,$ans+$a);
$a2 = rand($ans-$a  ,$ans+$a);
$a3 = rand($ans-$a  ,$ans+$a);

Upvotes: 0

Views: 638

Answers (1)

IMSoP
IMSoP

Reputation: 97718

As shown in previous answers (e.g. Generating random numbers without repeats, Simple random variable php without repeat, Generating random numbers without repeats) you can use shuffle to randomise a range, and then pick three items using array_slice.

The difference in your case is how you define the range:

  • Rather than 1 to 10, you want $ans - 10 to $ans + 10
  • You want to exclude the right answer

One way to build that is as two ranges: lower limit up to but not including right answer, and right answer + 1 up to upper limit.

function generate_wrong_answers($rightAnswer) {
    // Generate all wrong guesses from 10 below to 10 above, 
    // but miss out the correct answer
    $wrongAnswers = array_merge(
        range($rightAnswer - 10, $rightAnswer - 1),
        range($rightAnswer + 1, $rightAnswer + 10)
    );
    
    // Randomise
    shuffle($wrongAnswers);
    
    // Pick 3
    return array_slice($wrongAnswers, 0, 3);
}

Upvotes: 2

Related Questions