Title photo
frugal technology, simple living and guerrilla large-appliance repair
Sat, 26 Dec 2015

Generate a random number between 1 and 100 in JavaScript, Ruby, Python, Groovy, Perl and Bash

News that the random number generator in JavaScript was fixed (I didn't know it was broken) prompted me to wonder how easy (or hard) it is to generate a random integer between 1 and 100 in as many languages as I could.

Of course I used Google and the sites it found for me to come up with these methods.

Generating random numbers is important in programming, and it's very important that those numbers be truly random. That's why the problem with JavaScript's random numbers seems so serious, especially with JavaScript's ubiquity not just on the client (where it's carrying a heavier load than ever) but now the server via Node.js.

So you want to generate a random number between 1 and 100? Here are n ways to do it:

Random numbers in various computer languages:

JavaScript

Use node to run this line in your terminal (you do have node installed on your computer, right? If not, you should):

Math.floor(Math.random() * 100) + 1

Ruby

It's even easier in Ruby (use irb to run this in the console):

rand(100) + 1

Python

In Python, it takes a couple of lines. You can run this in the python console (type python at the command line, then start typing your commands):

import random print(random.randint(0,100))

Groovy

I have been experimenting with Groovy, a dynamic language that uses the JVM (the Java Virtual Machine). If you have Groovy installed, start the graphical Groovy console with the command groovyConsole.

Math.abs(new Random().nextInt() % 100 + 1)

Perl

While Perl doesn't have an interactive shell like Ruby and Python, you can run a one-liner from a terminal using the perl command. Here is a random number between 1 and 100 in Perl:

perl -le 'print int(rand(100)) + 1'

Bash

You can also do it in the Bash shell with $RANDOM:

echo $RANDOM % 100 + 1 | bc


Analysis: Ruby offers the easiest, most elegant way to generate a random integer from 1 to 100 with a one-liner. But you can do it in most every dynamic language.

Notes: I'm sure this can be done in a Perl one-liner