mirror of
https://github.com/SebastianStork/advent-of-code.git
synced 2026-01-21 12:11:34 +01:00
Solve 2024 day 2 in go
This commit is contained in:
parent
75def4d0e9
commit
af46c2fd1f
3 changed files with 1100 additions and 0 deletions
3
2024/go/day-02/go.mod
Normal file
3
2024/go/day-02/go.mod
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
module day-02
|
||||
|
||||
go 1.23
|
||||
1000
2024/go/day-02/input
Normal file
1000
2024/go/day-02/input
Normal file
File diff suppressed because it is too large
Load diff
97
2024/go/day-02/main.go
Normal file
97
2024/go/day-02/main.go
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func readInput() ([][]int, error) {
|
||||
content, err := os.ReadFile("input")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lines := strings.Split(strings.TrimSpace(string(content)), "\n")
|
||||
var reports [][]int
|
||||
|
||||
for _, line := range lines {
|
||||
parts := strings.Fields(line)
|
||||
levels := make([]int, len(parts))
|
||||
|
||||
for i, part := range parts {
|
||||
levels[i], _ = strconv.Atoi(part)
|
||||
}
|
||||
|
||||
reports = append(reports, levels)
|
||||
}
|
||||
|
||||
return reports, nil
|
||||
}
|
||||
|
||||
func isSafeReport(levels []int) (bool, int) {
|
||||
isIncreasing := levels[0] < levels[len(levels)-1]
|
||||
|
||||
for i := 1; i < len(levels); i++ {
|
||||
diff := levels[i] - levels[i-1]
|
||||
|
||||
if (isIncreasing && (diff <= 0 || diff > 3)) || (!isIncreasing && (diff >= 0 || diff < -3)) {
|
||||
return false, i
|
||||
}
|
||||
}
|
||||
|
||||
return true, -1
|
||||
}
|
||||
|
||||
func countSafeReports(reports [][]int) int {
|
||||
var count int
|
||||
|
||||
for _, levels := range reports {
|
||||
isSafe, _ := isSafeReport(levels)
|
||||
if isSafe {
|
||||
count++
|
||||
}
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
func countDampenedSafeReports(reports [][]int) int {
|
||||
var count int
|
||||
|
||||
for _, levels := range reports {
|
||||
isSafe, unsafeIndex := isSafeReport(levels)
|
||||
if isSafe {
|
||||
count++
|
||||
continue
|
||||
}
|
||||
|
||||
for i := unsafeIndex; i >= unsafeIndex-1 && i >= 0; i-- {
|
||||
var dampenedLevels []int
|
||||
dampenedLevels = append(dampenedLevels, levels[:i]...)
|
||||
dampenedLevels = append(dampenedLevels, levels[i+1:]...)
|
||||
|
||||
isSafe, _ = isSafeReport(dampenedLevels)
|
||||
if isSafe {
|
||||
count++
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
func main() {
|
||||
reports, err := readInput()
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
// Part one
|
||||
fmt.Println("Number of safe reports:", countSafeReports(reports))
|
||||
// Part two
|
||||
fmt.Println("Number of dampened safe reports:", countDampenedSafeReports(reports))
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue