0

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);
9
  • the number cannot be smaller and larger than 10 ??? 10 is not very random if thats the only number you allow Commented Mar 8, 2022 at 17:10
  • If you dont want the same random number more than once, thats not random, but all you have to do is check that the new random number is not already in the other variables. It would be easier if you stored the numbers in an array Commented Mar 8, 2022 at 17:12
  • 2
    10 the answer is 10 -- explainxkcd.com/wiki/images/f/fe/random_number.png Commented Mar 8, 2022 at 17:12
  • @IMSoP oh, Thank , comment and set duplicates actually, I reference these 3 questions before my post, google the first result is to use shuffle, but did not solve my problem Commented Mar 9, 2022 at 1:14
  • 1
    Ah now it is clearer, so if answer is 100 then the random numbers must be in the range 90 to 110. Is that what you mean? Commented Mar 9, 2022 at 8:34

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.