Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solve the random number logic

Tags:

php

random

logic

I have a function called myrand() which generates random number from 1 to 5. I want to make another function by using myrand() that will generate random number form 1 to 7. I write something like that.

function newrand() {
    return myrand()+2;
}

Above logic is not that I want it will never return me 1 or 2. I don't want to use any if condition so what should I do to make logic for random number.

like image 407
Muhammad Umar Avatar asked Jun 17 '26 20:06

Muhammad Umar


1 Answers

You have a function named rand() in PHP to do this. Try below code:

function newrand() {
    return rand(1, 7);
}

Or lets say your myrand() is something like this below code:

function myrand() {  return rand(1,5); }

What you can do is, pass the upperlimit to myrand() something like myrand(5) and myrand(7) instead of myrand() + 2. Eg below:

myrand($max) {
     return rand(1, $max);
}

and call it like this:

function newrand() {
    return myrand(7);
}
like image 164
Aniket Sahrawat Avatar answered Jun 20 '26 09:06

Aniket Sahrawat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!