AdventOfCode2021/15/main.go

129 lines
2.8 KiB
Go

package main
import (
"bufio"
"fmt"
"os"
"strconv"
"time"
)
func mustAtoi(line string) int {
i, _ := strconv.Atoi(line)
return i
}
func main() {
start := time.Now()
partOne()
duration := time.Since(start)
partTwo()
duration2 := time.Since(start)
fmt.Printf("p1: %s, p2: %s\n", duration, duration2-duration)
}
func makeScanner(test bool) *bufio.Scanner {
var f *os.File
if test {
f, _ = os.Open("inputs/testinput")
} else {
f, _ = os.Open("inputs/input")
}
reader := bufio.NewReader(f)
return bufio.NewScanner(reader)
}
type room struct {
row int
col int
distance int
cost int
}
func partOne() {
scanner := makeScanner(false)
grid := [100][100]room{}
col := 0
for scanner.Scan() {
line := scanner.Text()
for row, v := range line {
r := room{
distance: 1000,
cost: mustAtoi(string(v)),
}
grid[row][col] = r
}
col++
}
grid[0][0].distance = 0
for row := 0; row < 100; row++ {
for col := 0; col < 100; col++ {
if col+1 < 100 {
d := grid[row][col+1].distance
// if the cost of the space is less than the current known distance, this is the best route there
if d > grid[row][col+1].cost+grid[row][col].distance {
grid[row][col+1].distance = grid[row][col].distance + grid[row][col+1].cost
}
}
if row+1 < 100 {
d := grid[row+1][col].distance
// if the cost of the space is less than the current known distance, this is the best route there
if d > grid[row+1][col].cost+grid[row][col].distance {
grid[row+1][col].distance = grid[row][col].distance + grid[row+1][col].cost
}
}
}
}
fmt.Println(grid[99][99].distance)
}
func partTwo() {
scanner := makeScanner(false)
width := 100
scale := 5
len := width * scale
grid := [500][500]room{}
col := 0
for scanner.Scan() {
line := scanner.Text()
for row, v := range line {
for i := 0; i < scale; i++ {
for j := 0; j < scale; j++ {
cost := mustAtoi(string(v)) + i + j
if cost > 9 {
cost = ((mustAtoi(string(v)) + i + j) % 10) + 1
}
grid[row+i*width][col+j*width] = room{
row: row + i*width,
col: col + j*width,
distance: 100000,
cost: cost,
}
}
}
}
col++
}
grid[0][0].distance = 0
for row := 0; row < len; row++ {
for col := 0; col < len; col++ {
// if the cost of the space is less than the current known distance, this is the best route there
if col+1 < len {
if grid[row][col+1].distance > grid[row][col+1].cost+grid[row][col].distance {
grid[row][col+1].distance = grid[row][col].distance + grid[row][col+1].cost
}
}
if row+1 < len {
if grid[row+1][col].distance > grid[row+1][col].cost+grid[row][col].distance {
grid[row+1][col].distance = grid[row][col].distance + grid[row+1][col].cost
}
}
}
}
fmt.Println(grid[width*scale-1][width*scale-1])
}