Code Snippet: Random Integers

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Generate a Random Integer

Swift

```// Simulate casting a single, six-sided die and print the result
let firstDie = Int.random(in:1...6)
print(firstDie)
```
```// Simulate casting two six-sided dice and print the sum
let firstDie = Int.random(in:1...6)
let secondDie = Int.random(in:1...6)
print(firstDie+secondDie)
```

Python

```from random import randint
print(randint(1,6))
```
```from random import randint
print(randint(1,6) + randint(1,6))
```

Common Lisp

```; Seed the random state
(setf *random-state* (make-random-state t))

(defvar firstDie)
(setq firstDie (random 6))

(format t "~d~%"
firstDie)
```
```; Seed the random state
(setf *random-state* (make-random-state t))

(defvar firstDie)
(defvar secondDie)
(defvar dieResults)

(setq firstDie (random 6))
(setq secondDie (random 6))
(setq dieResults (+ firstDie secondDie))

(format t "~d~%"
dieResults)
```

Java

```// Import the Random class in java.util
Random random = new Random();

// Simulate rolling a 6 sided dice
// nextInt returns a pseudo random integer between 0(inclusive) and upperBound(exclusive)
int roll1 = random.nextInt(6) + 1; // Added the 1 to shift from 0 to 5 to 1 to 6
System.out.println("You rolled a " + roll1 + "!");

// Add a second die
int roll2 = random.nextInt(6) + 1;
System.out.println("You rolled a " + roll2 + "!");
int sum = roll1 + roll2;
System.out.println("Your sum is " + sum);
```