First time here? Check out the FAQ!

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

0 votes

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!


asked May 21, 2016 in Capytalk & Smalltalk by stephen-taylor (Adept) (1,620 points)

1 Answer

+2 votes

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


or in your case

r next * 3 + 13

Let us know how it goes!

answered May 22, 2016 by ssc (Savant) (127,080 points)
This totally works - thanks for the help! I hadn't even thought about scale and offset...