Skip to content

Commit 3e2e2cd

Browse files
committed
feat: Add sample for fair coin toss.
1 parent 965b5d0 commit 3e2e2cd

File tree

5 files changed

+38
-0
lines changed

5 files changed

+38
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ So far, the following exercises have been covered:
1313
- [Cons, Car, Cdr & co.](./cons) – implements a cons cell and the corresponding functions
1414
- [Continous maximum](./continuousmax/) – calculates the maximum of a sliding window
1515
- [Egyptian fractions](./egyptianfractions/) – calculates the "Egyptian Fractions" version of a given fraction
16+
- [Fair coin toss](./faircointoss/) – simulates a fair coin toss based on an unfair random function
1617
- [Fibonacci](./fibonacci/) – calculates the n-th Fibonacci number
1718
- [Floyd](./floyd/) – implements Floyd's cycle-finding "Tortoise and Hare" algorithm
1819
- [Heap](./heap/) – implements a heap from scratch, without using the built-in `container/heap` package

faircointoss/coin_side.go

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package faircointoss
2+
3+
type CoinSide string
4+
5+
const (
6+
CoinSideHeads CoinSide = "heads"
7+
CoinSideTails CoinSide = "tails"
8+
)

faircointoss/documentation.go

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// Package faircointoss simulates a fair coin toss based on an unfair random function.
2+
package faircointoss

faircointoss/fair.go

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package faircointoss
2+
3+
func FairCoinToss() CoinSide {
4+
for {
5+
firstCoinSide := UnfairCoinToss()
6+
secondCoinSide := UnfairCoinToss()
7+
8+
if firstCoinSide == secondCoinSide {
9+
continue
10+
}
11+
12+
return firstCoinSide
13+
}
14+
}

faircointoss/unfair.go

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package faircointoss
2+
3+
import "math/rand/v2"
4+
5+
func UnfairCoinToss() CoinSide {
6+
randomNumber := rand.Float64()
7+
8+
if randomNumber < 0.99 {
9+
return CoinSideHeads
10+
} else {
11+
return CoinSideTails
12+
}
13+
}

0 commit comments

Comments
 (0)