This repository has been archived by the owner on Dec 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgalton_board.go
99 lines (88 loc) · 1.91 KB
/
galton_board.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"log"
"math"
"math/rand"
"os"
"time"
)
const (
boardWidth = 800
boardHeight = 400
numBalls = 10000
imagePath = "galton_board.png"
)
type GaltonBoard struct {
width, height, numBalls int
distribution []int
random *rand.Rand
}
func NewGaltonBoard(width, height, numBalls int) *GaltonBoard {
return &GaltonBoard{
width: width,
height: height,
numBalls: numBalls,
distribution: make([]int, width),
random: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}
func (gb *GaltonBoard) Simulate() {
for i := 0; i < gb.numBalls; i++ {
gb.distribution[gb.calculateBin()]++
}
}
func (gb *GaltonBoard) CreateImage() *image.RGBA {
img := image.NewRGBA(image.Rect(0, 0, gb.width, gb.height))
maxCount := gb.findMaxCount()
for i, count := range gb.distribution {
height := int(float64(count) / float64(maxCount) * float64(gb.height))
for j := 0; j < height; j++ {
img.Set(i, gb.height-j-1, color.RGBA{255, 0, 0, 255})
}
}
return img
}
func (gb *GaltonBoard) calculateBin() int {
bin := gb.width / 2
for i := 0; i < gb.height; i++ {
if gb.random.Intn(2) == 0 {
bin--
} else {
bin++
}
}
return int(math.Min(math.Max(float64(bin), 0), float64(gb.width-1)))
}
func (gb *GaltonBoard) findMaxCount() int {
maxCount := 0
for _, count := range gb.distribution {
if count > maxCount {
maxCount = count
}
}
return maxCount
}
func saveImage(img *image.RGBA) {
f, err := os.Create(imagePath)
if err != nil {
log.Fatal(err)
}
defer f.Close()
if err := png.Encode(f, img); err != nil {
log.Fatal(err)
}
}
func runSimulation() {
gb := NewGaltonBoard(boardWidth, boardHeight, numBalls)
gb.Simulate()
img := gb.CreateImage()
saveImage(img)
}
func main() {
runSimulation()
fmt.Println(" ••• GALTON BOARD SIMUL COMPLETED ••• IMAGE ••• ", imagePath)
}