add day 2 part 2
This commit is contained in:
86
day2/test_reports_with_dampener.go
Normal file
86
day2/test_reports_with_dampener.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"strconv"
|
||||
"github.com/thoas/go-funk"
|
||||
)
|
||||
|
||||
|
||||
func check(e error) {
|
||||
if e != nil { panic(e) }
|
||||
}
|
||||
|
||||
func abs(n int) int {
|
||||
if n < 0 { return -n }
|
||||
return n
|
||||
}
|
||||
|
||||
func pop(arr []int, idx int) []int {
|
||||
out := make([]int, len(arr) - 1)
|
||||
|
||||
for i, elem := range arr {
|
||||
if i == idx {
|
||||
continue
|
||||
} else if i > idx {
|
||||
out[i - 1] = elem
|
||||
} else {
|
||||
out[i] = elem
|
||||
}
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func change(s []int) []int {
|
||||
out := make([]int, len(s) - 1)
|
||||
for i := range out {
|
||||
out[i] = s[i + 1] - s[i]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func validate_change(change []int) bool {
|
||||
all_neg := len( funk.Filter(change, func(x int) bool { return x >= 0 }).([]int) ) == 0
|
||||
all_pos := len( funk.Filter(change, func(x int) bool { return x <= 0 }).([]int) ) == 0
|
||||
all_abs_lt_4 := len( funk.Filter(change, func(x int) bool { return abs(x) > 3 }).([]int) ) == 0
|
||||
|
||||
return ( all_neg || all_pos ) && all_abs_lt_4
|
||||
}
|
||||
|
||||
func main() {
|
||||
// read in file as lines
|
||||
dat, err := os.ReadFile("data.txt")
|
||||
check(err)
|
||||
|
||||
valid := 0
|
||||
lines := strings.Split(string(dat), "\n")
|
||||
|
||||
// for every non empty line
|
||||
for _, line := range lines {
|
||||
if line == "" { continue }
|
||||
|
||||
// get numbers as array
|
||||
str_levels := strings.Split(line, " ")
|
||||
|
||||
// convert to integer
|
||||
levels := make([]int, len(str_levels))
|
||||
for j := range str_levels {
|
||||
levels[j], err = strconv.Atoi(str_levels[j])
|
||||
check(err)
|
||||
}
|
||||
|
||||
// check for valid series
|
||||
for i := range levels {
|
||||
slice := pop(levels, i)
|
||||
if validate_change(change(slice)) {
|
||||
valid++
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println(valid)
|
||||
}
|
||||
Reference in New Issue
Block a user