JSFiddle - React, Tailwind, and code Playground
HTML
Number of coin pairs to flip: <input type="text" id="flipno" value="1000"><br>
<button type="button" onclick="Generate()">Flip coins</button><br>
Two Heads: <span id="TT"></span><br>
One Each: <span id="HT"></span><br>
Two Tails: <span id="HH"></span><br>
<br>
Numer of pairs with one head where the other is tail: <span id="T"></span><br>
Numer of pairs with one head where the other is head: <span id="H"></span><br>
Frequency of "other" being a head: <span id="otherHfreq"></span><br>
<br>
Total number of heads: <span id="Tno"></span><br>
Total number of tails: <span id="Hno"></span><br>
Frequency of heads: <span id="Hfreq"></span><br>
JavaScript
function Generate() {
// Get number of pair flips to do
var n = parseInt(document.getElementById("flipno").value);
// These store total number of heads and tails
totalH = 0;
totalT = 0;
// These store total number of combos ignoring order
TT = 0;
HT = 0;
HH = 0;
// These store number of times where other coin is tail or head when one is heads
otherH = 0;
otherT = 0;
for (i = 0; i < n; i++) {
// 50-50 chance for first coin flip
if (Math.random() < 0.5)
coins = "H";
else
coins = "T";
// 50-50 chance for second coin flip
if (Math.random() < 0.5)
coins += "H";
else
coins += "T";
// coins now contains a string listing two coin flips: HH, HT, TH, TT
if (coins == "HH") {
HH += 1;
totalH += 2;
otherH += 1;
} else if ((coins == "HT") || (coins == "TH")) {
HT += 1;
totalH += 1;
totalT += 1;
otherT += 1;
} else if (coins == "TT") {
TT += 1;
totalT += 2;
}
}
// Dump all of the numbers to html so user can see them
document.getElementById("TT").innerHTML = TT;
document.getElementById("HT").innerHTML = HT;
document.getElementById("HH").innerHTML = HH;
document.getElementById("T").innerHTML = otherT;
document.getElementById("H").innerHTML = otherH;
document.getElementById("Tno").innerHTML = totalT;
document.getElementById("Hno").innerHTML = totalH;
document.getElementById("otherHfreq").innerHTML = 100*otherH / (otherT + otherH) + "%";
document.getElementById("Hfreq").innerHTML = 100*totalH / (totalT + totalH)+ "%";
}