A random number generator will generate a number that cannot be predicted.
Although, it is impossible to generatetruerandom number on a computer.
Please take a look at line 3 with theimport
statement. This tells the compiler that, to be able to compile this code, it will need to fetch this other component. In most Scala code you are going to see in your professional life, there will beimport
statements at the beginning of the files. But, do not worry, those are usually added automatically by the development environment (IDE) so you don't have to care for it quite yet.
You recognize thenew
from the SKB aboutclass
. It tells us thatscala.util.Random
is aclass
that needs to be instantiated before able to use it.
Now we have a random generator, what can we do with it? You can generate a lot of different types, here we are only focusing onInt
to simplify things but you can take a look atscala.util.Random documentationto see what else is available.
Try running the code several times, do you see that the number generated are different each time?
However, the number generated by the generator started with a seed always generate the same series of number. This is because there are no true random in a computer. A random generator is a function that given a number generate a new number. The starting number is theseed
. If you are playing procedurally generated games, such as Minecraft for instance, this is what theseed
is for, it initializes the random generator.
One interesting part of this SKB is therandomInt
method. Did you figure out what was the missing part ? If not, here is the solution:
rand.nextInt(max - min) + min
The first part (rand.nextInt(max - min)
) will return an Integer between0
andmax - min
but we want something betweenmin
andmax
. We need to addmin
. That way, we generate a number between0 + min
andmax - min + min
, which resolve tomin
tomax
.
There is a little brain candy at the end of the code, did you notice it ?for
. This is called afor-comprehension. We are going to go more into details about it in up-coming SKBs.
An other brain candy is therange
. In Scala, you can describe a range of number in different ways:
0 to 2
will generate the numbers0, 1, 2
0 until 2
which will generate the numbers0, 1
0 until 10 by 3
which will generate the numbers0, 3, 6, 9