/
main.go
128 lines (106 loc) · 2.54 KB
/
main.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
package main
import (
"fmt"
"io/ioutil"
"strings"
)
const (
FLOOR, EMPTY_SEAT, OCCUPIED_SEAT = ".", "L", "#"
)
func main() {
content, err := ioutil.ReadFile("input.txt")
checkErr(err)
lines := strings.Split(string(content), "\n")
seats := make([][]string, len(lines))
seatspart2 := make([][]string, len(lines))
for i, line := range lines {
seats[i] = make([]string, len(line))
seatspart2[i] = make([]string, len(line))
for j:=0;j<len(line);j++ {
seats[i][j] = string(line[j])
seatspart2[i][j] = string(line[j])
}
}
for numOfChanges := 1; numOfChanges > 0; seats, numOfChanges = moveOfSeatsPlease(seats, 4, false) {}
fmt.Println("part 1:",countState(seats, OCCUPIED_SEAT))
for numOfChanges := 1; numOfChanges > 0; seatspart2, numOfChanges = moveOfSeatsPlease(seatspart2, 5, true) {}
fmt.Println("part 2:", countState(seatspart2, OCCUPIED_SEAT))
}
func countState(s [][]string, desiredState string) (count int) {
for x:=0;x<len(s);x++ {
for y:=0;y<len(s[x]);y++ {
if s[x][y] == desiredState {
count++
}
}
}
return count
}
func moveOfSeatsPlease(s [][]string, maxAdjacents int, checkViews bool) ([][]string, int) {
copiedS := make([][]string, len(s))
copy(copiedS, s)
numOfChanges := 0
for x:=0;x<len(s);x++ {
copiedS[x] = make([]string, len(s[x]))
copy(copiedS[x], s[x])
for y:=0;y<len(s[x]);y++ {
switch s[x][y] {
case EMPTY_SEAT:
if occuppiedAdjacents(s, x, y, checkViews) == 0 {
copiedS[x][y] = OCCUPIED_SEAT
numOfChanges++
}
case OCCUPIED_SEAT:
if occuppiedAdjacents(s, x, y, checkViews) >= maxAdjacents {
copiedS[x][y] = EMPTY_SEAT
numOfChanges++
}
}
}
}
return copiedS, numOfChanges
}
func occuppiedAdjacents(s [][]string, x int, y int, checkViews bool) (adjacents int) {
for i:=x-1;i<=x+1;i++ {
if i<0 || i>= len(s) {
continue
}
for j:=y-1;j<=y+1;j++ {
if j<0 || j>= len(s[i]) || (j == y && i == x) {
continue
}
if s[i][j] == OCCUPIED_SEAT {
adjacents++
} else if s[i][j] == FLOOR && checkViews {
tmpi, tmpj := i, j
for {
tmpi = incDecOrUnmodVar(tmpi, i, x)
tmpj = incDecOrUnmodVar(tmpj, j, y)
if tmpi < 0 || tmpj < 0 || tmpi >= len(s) || tmpj >= len(s[i]) {
break
}
if val := s[tmpi][tmpj]; val != FLOOR {
if val == OCCUPIED_SEAT {
adjacents++
}
break
}
}
}
}
}
return adjacents
}
func incDecOrUnmodVar(tmpi int, i int, x int) int {
if i<x {
tmpi--
} else if i>x {
tmpi++
}
return tmpi
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}