Run ❯
Get your
own
website
×
Change Orientation
Change Theme, Dark/Light
Go to Spaces
Python
JavaScript
Java
C++
import random numExperiments = 1000 totalRolls = 0 for i in range(numExperiments): count = 0 while True: dice = random.randint(1,6) count += 1 if dice == 6: break totalRolls += count print('Doing ' + str(numExperiments) + ' experiments') print('Average number of rolls to get 6 is ' + str(totalRolls/numExperiments)) #Python
let numExperiments = 1000; let totalRolls = 0; for (let i = 0; i < numExperiments; i++) { let count = 0; while (true) { let dice = Math.floor(Math.random() * 6) + 1; count++; if (dice === 6) { break; } } totalRolls += count; } console.log("Doing " + numExperiments + " experiments"); console.log("Average number of rolls to get 6 is " + totalRolls/numExperiments); //JavaScript
import java.util.Random; public class Main { public static void main(String[] args) { Random random = new Random(); int numExperiments = 1000; int totalRolls = 0; for (int i = 0; i < numExperiments; i++) { int count = 0; while (true) { int dice = random.nextInt(6) + 1; // 1 to 6 count++; if (dice == 6) { break; } } totalRolls += count; } System.out.println("Doing " + numExperiments + " experiments"); double average = (double) totalRolls / numExperiments; System.out.println("Average number of rolls to get 6 is " + average); } } //Java
#include
#include
#include
#include
using namespace std; int main() { srand(time(nullptr)); // Seed the random generator int numExperiments = 1000; int totalRolls = 0; for (int i = 0; i < numExperiments; i++) { int count = 0; while (true) { int dice = rand() % 6 + 1; // 1 to 6 count++; if (dice == 6) { break; } } totalRolls += count; } cout << "Doing " + to_string(numExperiments) + " experiments\n"; double average = static_cast
(totalRolls) / numExperiments; cout << "Average number of rolls to get 6 is " + to_string(average) + "\n"; return 0; } //C++
Python result:
JavaScript result:
Java result:
CPP result:
Doing 1000 experiments
Average number of rolls to get 6 is 5.954
Doing 1000 experiments
Average number of rolls to get 6 is 5.954
Doing 1000 experiments
Average number of rolls to get 6 is 5.954
Doing 1000 experiments
Average number of rolls to get 6 is 5.954