Difference between revisions of "Generate a random number"

From CodeCodex

(add bash example)
Line 1: Line 1:
 
==Implementations==
 
==Implementations==
  
 +
===bash===
 +
Prints a random integer.
 +
<HIGHLIGHTSYNTAX language="bash">
 +
val="$RANDOM"
 +
echo $RANDOM
 +
</HIGHLIGHTSYNTAX>
  
 
===PHP===
 
===PHP===
Line 82: Line 88:
 
</pre>
 
</pre>
  
 +
[[Category:bash]]
 
[[Category:C]]
 
[[Category:C]]
 
[[Category:Java]]
 
[[Category:Java]]

Revision as of 10:50, 26 November 2009

Implementations

bash

Prints a random integer. <HIGHLIGHTSYNTAX language="bash"> val="$RANDOM" echo $RANDOM </HIGHLIGHTSYNTAX>

PHP

<highlightsyntax>

 $int = rand(99);
 //$int is a random number between 0 and 99 inclusive

</highlightsyntax>

C

#include <stdlib.h>
#include <time.h>

srand(time(NULL)); /* initialize random seed */
rand();            /* Generate a random int from 0 to RAND_MAX */
rand() % 100;      /* Generate a random int from 0 to 99 */
rand() % 100 + 1;  /* Generate a random int from 1 to 100 */
rand() % 30 + 100; /* Generate a random int from 100 to 129 */

Java

Generate a random int from 0 to n

 java.util.Random rand = new java.util.Random();
 i = rand.nextInt(n+1);

OCaml

# Random.int 15;;
- : int = 9

Perl

rand; # Generate a random real number between 0 and 1
rand(100); # Generate a random real number between 0 and 100
int(rand(100)); # Generate a random integer between 0 and 99

Python

import random

# Generate a random integer between 0 and n, exclusive
random.randrange(n)

# Generate a random integer between m and n, inclusive
random.randrange(m, n + 1)

Ruby

Generate a random integer between 0 and n, exclusive

rand(n)

Seed7

Generate a random integer between m and n inclusive

 rand(m, n)

Zsh

# Generate pseudo-random number between 0 and 32767.
$RANDOM

# Generate pseudo-random number between 0 and 9.
$RANDOM % 10

# Or

typeset -F SECONDS
typeset -F6 SECONDS
${SECONDS#*.} % 10

# Generate pseudo-random number between 0 and 1 using module of mathematical functions.
zmodload -i zsh/mathfunc
rand48()