Last active
June 22, 2020 20:15
-
-
Save pcasaretto/d54e5fa9aad4ea762a0d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
) | |
func rollDice() int { | |
return rand.Intn(6) + 1 | |
} | |
type generator func() int | |
type strategy func(generator) generator | |
func applyStrategy(g generator, strats ...strategy) generator { | |
for _, s := range strats { | |
g = s(g) | |
} | |
return g | |
} | |
func reroll(g generator) generator{ | |
return func() int { | |
n := g() | |
if n < 5 { | |
return g() | |
} | |
return n | |
} | |
} | |
func addOne(g generator) generator { | |
return func() int { | |
n := g() | |
if n < 5 { | |
return n + 1 | |
} | |
return n | |
} | |
} | |
func successRate(rolls []int) float64 { | |
var oks int | |
for _, v := range rolls { | |
if v == 5 || v == 6 { | |
oks++ | |
} | |
} | |
return float64(oks) / float64(len(rolls)) | |
} | |
func generateRolls(n int, gen func() int) []int { | |
var rolls []int | |
for i := 0; i < n; i++ { | |
rolls = append(rolls, gen()) | |
} | |
return rolls | |
} | |
func main() { | |
fmt.Println(successRate(generateRolls(1000000, rollDice))) | |
fmt.Println(successRate(generateRolls(1000000, applyStrategy(rollDice, reroll)))) | |
fmt.Println(successRate(generateRolls(1000000, applyStrategy(rollDice, addOne)))) | |
fmt.Println(successRate(generateRolls(1000000, applyStrategy(rollDice, addOne, reroll)))) | |
fmt.Println(successRate(generateRolls(1000000, applyStrategy(rollDice, reroll, addOne)))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment