<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width" />
<title>Hello, world!</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Hello, world! RandomToss Calculator.</h1>
<label for="var1">Heads Probability:</label>
<input type="number" id="var1" required>
<br>
<br>
<button id="run">Calculate</button>
<br>
<p id="debug"></p>
<p id="result"></p>
<p id="summary"></p>
<script>
function randomToss() {
const probabilityInput = document.getElementById("var1");
const probability = parseFloat(probabilityInput.value);
const debugElement = document.getElementById("debug");
const resultElement = document.getElementById("result");
const summaryElement = document.getElementById("summary");
// Ensure probability is within the valid range of 0 to 1
if (probability < 0 || probability > 1) {
debugElement.textContent = `Input is invalid! Try "0.5" for probability input."`;
resultElement.textContent = ``;
summaryElement.textContent = ``;
return;
}
let result = "";
let heads = 0, tails = 0;
for (let n = 0; n < 100; n++) {
// Generate a random float between 0 and 1
const r = Math.random();
// Determine the outcome based on the probability
if (r <= probability) {
result += `${n+1}: Heads, `; heads++;
} else {
result += `${n+1}: Tails, `; tails++;
}
}
debugElement.textContent = ``;
resultElement.textContent = result;
summaryElement.textContent = `SUMMARY: heads are ${heads}, tails are ${tails}.`;
}
// Attach an event listener to the calculate button
const calculateButton = document.getElementById("run");
calculateButton.addEventListener("click", randomToss);
</script>
</body>
</html>