Code Snippet: Random Integers

From Coder Merlin
Jump to navigation Jump to search

Generate a Random Integer[edit]

Swift[edit]

// 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[edit]

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

Common Lisp[edit]

; 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[edit]

// 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);


CoderMerlin™ proudly recommends:
HintIcon.png

Your purchase via these links helps keep  Coder Merlin™ 's orbuculum ablaze. As an Amazon Associate we earn from qualifying purchases. Thank you for your support!


Designed with pride in Silicon Valley, CA, USA