# Smalltalk - how to choose randomly from a range of numbers?

1,220 views

I'm adapting the Text to Pitch prototype, for a simple DNA project, with a,c,t,g. Inisde the script I have the following -

(nbr == 97) ifTrue: [nbr := 13]. "a"

Where the first number is an ASCII code, and the second number is a nn for a KeyMappedMultismaple. What I'd like to do is choose from a range of numbers, like this -

(nbr == 97) ifTrue: [nbr := randomly select from the range 13-16].

I found "Interval", from online Smalltalk documentation:

(nbr == 97) ifTrue: [nbr := Interval from: 13 to: 16].

But I can't find the code to randomly select a number from the Interval. Thanks for any help, from an amateur programmer!

In Smalltalk, you could create a source of random numbers by creating a new instance of the class Random as:

| r |

r := Random new.

Once you have that source, you can continue to ask it for the next random number by sending it the message next.  For example:

r next

would be a random number (from a uniform distribution) between 0 and 1.

In your example, you want the range of (0,1) to be scaled and offset to the range (13,16).  In general, the way to do that would be:

<randomNumberBetween0and1> * newRange + offset

where the range is

maximumValue - minimumValue

and the offset is

minimumValue