96 lines
1.4 KiB
Go
96 lines
1.4 KiB
Go
|
|
package main
|
||
|
|
|
||
|
|
import (
|
||
|
|
"bufio"
|
||
|
|
"fmt"
|
||
|
|
"os"
|
||
|
|
"strconv"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
func check(e error) {
|
||
|
|
if e != nil {
|
||
|
|
panic(e)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func is_safe(levels []int) bool {
|
||
|
|
all_diffs_neg := true
|
||
|
|
all_diffs_pos := true
|
||
|
|
|
||
|
|
prev := levels[0]
|
||
|
|
for i, level := range levels {
|
||
|
|
if i == 0 {
|
||
|
|
prev = level
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
|
||
|
|
diff := level - prev
|
||
|
|
if diff > 3 || diff < -3 || diff == 0 {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
|
||
|
|
all_diffs_pos = all_diffs_pos && diff > 0
|
||
|
|
all_diffs_neg = all_diffs_neg && diff < 0
|
||
|
|
prev = level
|
||
|
|
}
|
||
|
|
|
||
|
|
return all_diffs_neg || all_diffs_pos
|
||
|
|
}
|
||
|
|
|
||
|
|
func is_safe_with_dampener(levels []int) bool {
|
||
|
|
if is_safe(levels) {
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
|
||
|
|
for i := range levels {
|
||
|
|
damped_levels := make([]int, 0, len(levels)-1)
|
||
|
|
for j, val := range levels {
|
||
|
|
if i == j {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
|
||
|
|
damped_levels = append(damped_levels, val)
|
||
|
|
}
|
||
|
|
|
||
|
|
if is_safe(damped_levels) {
|
||
|
|
return true
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
|
||
|
|
func main() {
|
||
|
|
f, err := os.Open("./two.txt")
|
||
|
|
defer f.Close()
|
||
|
|
check(err)
|
||
|
|
|
||
|
|
n_safe := 0
|
||
|
|
n_dampener_safe := 0
|
||
|
|
|
||
|
|
scanner := bufio.NewScanner(f)
|
||
|
|
for scanner.Scan() {
|
||
|
|
|
||
|
|
line := scanner.Text()
|
||
|
|
fields := strings.Fields(line)
|
||
|
|
|
||
|
|
levels := make([]int, 0, 5)
|
||
|
|
|
||
|
|
for _, field := range fields {
|
||
|
|
level, err := strconv.Atoi(field)
|
||
|
|
check(err)
|
||
|
|
levels = append(levels, level)
|
||
|
|
}
|
||
|
|
if is_safe(levels) {
|
||
|
|
n_safe += 1
|
||
|
|
}
|
||
|
|
if is_safe_with_dampener(levels) {
|
||
|
|
n_dampener_safe += 1
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fmt.Println(n_safe)
|
||
|
|
fmt.Println(n_dampener_safe)
|
||
|
|
}
|