attempt 1 at day 2 part 1

This commit is contained in:
Neil Hanlon 2024-12-06 11:40:07 -05:00
parent f0e842308b
commit 232a56d130
Signed by: neil
GPG Key ID: 705BC21EC3C70F34
3 changed files with 1126 additions and 0 deletions

1000
02/input Normal file

File diff suppressed because it is too large Load Diff

6
02/input-ex Normal file
View File

@ -0,0 +1,6 @@
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9

120
02/main.go Normal file
View File

@ -0,0 +1,120 @@
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
type Report struct {
number int
levels []int
valid bool
direction string
}
// Reports stored one per line with levels in each column.
// In safe reports, the levels are either all increasing or all decreasing AND
// Any two adjacent levels differ by at least one and at most three.
func main() {
input, err := os.ReadFile("input")
if err != nil {
fmt.Println(err)
}
var reports []Report
lines := strings.Split(string(input), "\n")
for idx, val := range lines[0 : len(lines)-1] {
reportFields := strings.Fields(val)
report := Report{
number: idx,
valid: true,
direction: "ASC",
}
for _, field := range reportFields {
reportVal, err := strconv.Atoi(field)
if err != nil {
break
}
report.valid = IsValidReport(&report, reportVal)
report.levels = append(report.levels, reportVal)
}
reports = append(reports, report)
}
var valid int
for _, report := range reports {
fmt.Printf("%v\n", report)
if report.valid {
valid++
}
}
fmt.Printf("Total: %v Valid %v\n", len(reports), valid)
}
func IsValidReport(report *Report, reportVal int) bool {
if !report.valid {
return false
}
valid := true
if len(report.levels) >= 1 {
fmt.Printf("===reportVal===: %v\n", reportVal)
fmt.Printf("levels: %v\n", report.levels)
last := report.levels[len(report.levels)-1]
// if len(report.levels) == 1 {
// last = 0
// }
fmt.Printf("last: %v\n", last)
// Determine direction
fmt.Printf("direction: %v\n", report.direction)
if len(report.levels) == 1 {
report.direction = DetermineDirection(report.levels[0], reportVal)
}
fmt.Printf("direction: %v\n", report.direction)
fmt.Printf("valid: %v\n", valid)
switch report.direction {
case "ASC":
if last > reportVal {
valid = false
}
case "DESC":
if last < reportVal {
valid = false
}
}
fmt.Printf("valid: %v\n", valid)
// fmt.Printf("abs(%v-%v)=%v\n", reportVal, last, Abs(reportVal-last))
// Check if our deltas are OK
delta := Abs(reportVal - last)
fmt.Printf("delta: %v\n", delta)
// fmt.Printf("abs(%v-%v)=%v\n", reportVal, last, Abs(reportVal-last))
if delta < 1 || delta > 3 {
valid = false
}
fmt.Printf("valid: %v\n", valid)
fmt.Printf("\n\n")
}
return valid
}
func DetermineDirection(one, two int) string {
diff := one - two
if diff < 0 {
return "ASC"
}
return "DESC"
}
func Abs(input int) int {
if input < 0 {
return -input
}
return input
}