ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Not sure if programming forum is best but I am trying a simple script on Fedora for a random number generator. I know it is not truly random and am ok with a cheesy hack.
I searched and found "generate random number in specific range" examples:
generating a random number between 11 and 30: echo $[ $RANDOM % 20 + 11 ]
It seems to work, but where does 20 come into anything? In other examples I found, the first number is the high end of the range. If I wanted something random between 10 & 15 what would I use?
$RANDOM % 20 generates a random number betwwen 0 and 19, add 11 to get a number from 11 to 30
For a value between 10 & 15, use $[$RANDOM % 6 + 10]
I found a couple of pages that basically said the same thing (the example) and the man file, and not explaining how it was actually formed. I understand it now.
To elaborate on the previous posts basically $RANDOM outputs a signed 16 bit integer i.e a number between 0-32767
To output a smaller range you use the modulo function. The modulo function returns the remainder of an integer division operation. You would take the modulo using the value of the desired range then add the offset.
Quote:
$RANDOM % 6 + 1
As another example to output a random number from 1-6 you use 6 for the modulo which outputs 0-5 then add 1. A simpler function is shuf which does all the range calculations for you. For the same example
Quote:
shuf -i 1-6 -n 1
Will output a random number between 1-6 and display 1 number instead the default which is 20. See man pages for shuf for more details.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.