Completed day2 for go
This commit is contained in:
parent
b1010b155e
commit
02a1c0a90a
4 changed files with 1107 additions and 0 deletions
|
|
@ -74,6 +74,10 @@ func main() {
|
|||
secondCol = append(secondCol, input[1])
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
answer := Part1(firstCol, secondCol)
|
||||
fmt.Println(answer)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,78 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func isSafe(row []int) bool {
|
||||
increasing := true
|
||||
decreasing := true
|
||||
valid := true
|
||||
|
||||
for i := 1; i < len(row); i++ {
|
||||
diff := math.Abs(float64(row[i]) - float64(row[i-1]))
|
||||
|
||||
if diff < 1 || diff > 3 {
|
||||
valid = false
|
||||
break
|
||||
}
|
||||
|
||||
if row[i] < row[i-1] {
|
||||
increasing = false
|
||||
}
|
||||
|
||||
if row[i] > row[i-1] {
|
||||
decreasing = false
|
||||
}
|
||||
}
|
||||
|
||||
if valid && (increasing || decreasing) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func Part1(rows [][]int) int {
|
||||
safe := 0
|
||||
for _, row := range rows {
|
||||
if isSafe(row) {
|
||||
safe += 1
|
||||
}
|
||||
}
|
||||
|
||||
return safe
|
||||
}
|
||||
|
||||
func Part2(rows [][]int) int {
|
||||
safe := 0
|
||||
for _, row := range rows {
|
||||
if isSafe(row) {
|
||||
safe += 1
|
||||
continue
|
||||
}
|
||||
|
||||
for i := 0; i < len(row); i++ {
|
||||
modified := make([]int, len(row)-1)
|
||||
copy(modified[:i], row[:i])
|
||||
copy(modified[i:], row[i+1:])
|
||||
|
||||
if isSafe(modified) {
|
||||
safe += 1
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return safe
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
|
|
@ -19,4 +87,33 @@ func main() {
|
|||
panic(err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
var rows [][]int
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
|
||||
var row []int
|
||||
|
||||
for _, num := range strings.Fields(line) {
|
||||
n, err := strconv.Atoi(num)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
row = append(row, n)
|
||||
}
|
||||
|
||||
rows = append(rows, row)
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
answer := Part1(rows)
|
||||
fmt.Println(answer)
|
||||
|
||||
answer = Part2(rows)
|
||||
fmt.Println(answer)
|
||||
}
|
||||
|
|
|
|||
6
2024/go/test.txt
Normal file
6
2024/go/test.txt
Normal 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
|
||||
1000
2024/inputs/day2.txt
Normal file
1000
2024/inputs/day2.txt
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue