AdventOfCode2020/13/main.go

90 lines
1.6 KiB
Go

package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
"strings"
"time"
)
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 partOne() {
f, _ := os.Open("input")
reader := bufio.NewReader(f)
scanner := bufio.NewScanner(reader)
busWaitTimes := map[int]int{}
shortestWait := -1
// don't actually need loop logic for a two-line input
scanner.Scan()
ts := scanner.Text()
currentTimestamp, _ := strconv.Atoi(ts)
scanner.Scan()
buses := strings.Split(scanner.Text(), ",")
for _, b := range buses {
if b != "x" {
j, _ := strconv.Atoi(b)
busWaitTimes[j] = (((currentTimestamp / j) + 1) * j) - currentTimestamp
if shortestWait == -1 || busWaitTimes[shortestWait] > busWaitTimes[j] {
shortestWait = j
}
}
}
fmt.Println(busWaitTimes[shortestWait] * shortestWait)
}
type bus struct {
route float64
offset float64
}
func partTwo() {
f, _ := os.Open("input")
reader := bufio.NewReader(f)
scanner := bufio.NewScanner(reader)
buses := []bus{}
scanner.Scan() // discard first line
scanner.Scan()
line := strings.Split(scanner.Text(), ",")
for i, b := range line {
if b != "x" {
j, _ := strconv.Atoi(b)
buses = append(buses, bus{
route: float64(j),
offset: float64(i),
})
}
}
t := float64(0)
offset := buses[0].route
loop:
t = t + offset
offset = 1
for i := range buses {
if math.Remainder(t+buses[i].offset, buses[i].route) != 0 {
goto loop
} else {
offset = offset * buses[i].route
}
}
fmt.Println(int(t))
}