Introduction To Ruby
The following example generates random integers,
# Random Integers
a = rand(10) # Integer from 0 - 9
b = rand(10)+10 # Integer from 10 - 19
c = rand(10)-5 # Integer from -5 to 4
Study these examples carefully. The number in the brackets is referred to as max. The random number that is generated will be from 0 to max - 1. Almost all programming languages use this kind of exclusivity when specifying random integers. People who are new to programming often fail to read references carefully and wonder why, for example, their dice program cannot generate a 6. Adding or subtracting from the number that is generated allows you to generate random numbers within a given range.
If you don't place a number in the brackets, you generate a floating point number that is greater than or equal to 0.0 and less than 1.0. The following example demonstrates this,
# Random Floats
a = rand() # Float greater than or equal to 0.0, less than 1.0
b = rand()*10 # Float greater than or equal to 0.0, less than 10.0
Using multiplication, addition and subtraction, you can get a random floating point number in the range that you want.
- Make a program that simulates the rolling of two dice. Output the result of each roll as well as the total.
- Output 6 lotter numbers (1 - 49). Don't worry about duplicates at this stage but make sure that it is possible to generate a 49.