-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain2.go
135 lines (115 loc) · 2.13 KB
/
main2.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
const size = 100
func main() {
scanner := bufio.NewScanner(os.Stdin)
grid := &[size][size]bool{}
var row, col int
for scanner.Scan() {
col = 0
line := strings.TrimSpace(scanner.Text())
if len(line) != size {
log.Fatal("line not size chars")
}
for _, c := range line {
if c == '#' {
grid[row][col] = true
}
col++
}
row++
}
for i := 0; i < size; i++ {
grid = step(grid)
// Uncomment following to see the animation in the terminal
//fmt.Print("\033[H\033[2J") //clear the screen
//printGrid(grid)
//time.Sleep(800 * time.Millisecond)
}
fmt.Println(countTrue(grid))
}
// Conway's Game of Life rules.
func step(in *[size][size]bool) *[size][size]bool {
out := &[size][size]bool{}
for i := 0; i < size; i++ {
for j := 0; j < size; j++ {
neighborsOn := neighborsOn(in, i, j)
if in[i][j] {
switch neighborsOn {
case 2, 3:
out[i][j] = true
default:
out[i][j] = false
}
} else {
if neighborsOn == 3 {
out[i][j] = true
} else {
out[i][j] = false
}
}
}
}
out[0][0] = true
out[0][size-1] = true
out[size-1][0] = true
out[size-1][size-1] = true
return out
}
// count the neighbors that are turned on
func neighborsOn(in *[size][size]bool, x int, y int) int {
trues := 0
// -1, 0, +1 in both axis
for δx := -1; δx < 2; δx++ {
x2 := x + δx
// if out of bounds, count as off.
if x2 < 0 || x2 >= size {
continue
}
for δy := -1; δy < 2; δy++ {
y2 := y + δy
// if out of bounds, count as off.
if y2 < 0 || y2 >= size {
continue
}
// ignore the cell itself
if x == x2 && y == y2 {
continue
}
// count if light is on
if in[x2][y2] {
trues++
}
}
}
return trues
}
func countTrue(in *[size][size]bool) int {
count := 0
for i := 0; i < size; i++ {
for j := 0; j < size; j++ {
if in[i][j] {
count++
}
}
}
return count
}
func printGrid(in *[size][size]bool) {
for i := 0; i < size; i++ {
for j := 0; j < size; j++ {
if in[i][j] {
fmt.Print("#")
} else {
fmt.Print(".")
}
}
fmt.Println()
}
}