How to determine if two random values are next?

Asked

Viewed 43 times

1

I have a question I’d like answers to.

I have a RAND function that generates values from 1 to 20.

What I intend to do is:

Se o valor $rand1 tiver perto do valor $rand2
echo ok

How do I say "Near" in PHP?

  • 4

    Depends, what you consider "next"?

  • 3

    Set a value to 'close' and subtract the two numbers? would that be?

  • Yes, if rand1 is 12 and rand2 is 13, echo is close. .

  • 1

    As much as one example of what you have tried is missing, I do not agree that this question is negative!

2 answers

8

Yeah, the way is what @rray commented:

function perto($a, $b)
{
    $limite = 2;
    return abs($a - $b) <= $limite;
}

if(perto($rand1, $rand2)) {
    echo 'perto';
}
  • I liked this one, it was the right one and it solves my problem. Thank you

  • Could you explain how the @bfvaretto method works? I don’t know anything about PHP, I found the question interesting.

  • 1

    Alias + 1, I understand what happens in your method.

1

Try this logic, I did not test.

if ($rand1 > $rand2) {
    if ($rand1 - $rand2 == 1) {
        echo "Esta perto";
    }
    else {
        echo "Está longe";
    }
}
else if ($rand2 > $rand1) {
    if ($rand2 - $rand1 == 1) {
        echo "Esta perto";
    }
    else {
        echo "Está longe";
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.