s c h e m a t i c s : c o o k b o o k

/ WebHome / TOC / NumberChapter / Cookbook.NumberRecipeRandomNumber

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Generating Random Numbers

Problem

You want a random number from a given range. For example, you wish to randomly select one element from an array, simulate rolling a die in a game of chance, or generate a random password.

Solution

Use (random-integer n) function from SRFI27?. It returns a random exact integer in the range of 0 to n-1.

500 Can't connect to 127.0.0.1:8778 (connect: Connection refused)

Discussion

This code generates and prints a random integer between 25 and 75, inclusive:

500 Can't connect to 127.0.0.1:8778 (connect: Connection refused)

In the example, we want to limit the range to 25 to 75, so we add 25 to the result of the random function. This means we really want a random number between 0 and 50, so we give the random function the argument 51 (since the generated number is always from 0 to n-1).

The canonical application for this kind of number generation is the random selection of an element from a vector:

500 Can't connect to 127.0.0.1:8778 (connect: Connection refused)

Another common example is generating a random password. For this example, we will make use of SRFI 14 (Character Set Library) and SRFI 42 (List Comprehensions):

500 Can't connect to 127.0.0.1:8778 (connect: Connection refused)

See Also

NumberRecipeBigRandomNumber

CookbookForm
TopicType: Recipe
ParentTopic: NumberRecipes
TopicOrder: 070

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest