adventofcode/2019/day03/main.go

126 lines
2.2 KiB
Go
Raw Normal View History

2019-12-03 14:25:33 +00:00
package main
import (
"bufio"
"fmt"
"log"
"math"
"os"
"strconv"
"strings"
)
const MaxInt = int(^uint(0) >> 1)
func main() {
inp := StdinToStringSlice()
part1(inp)
}
func part1(inp []string) {
var allWires []*Wire
for _, v := range inp {
wire := NewWire()
wrk := strings.Split(v, ",")
for _, p := range wrk {
wire.Go(p)
}
allWires = append(allWires, wire)
}
var shortestCoord, fewestStepsCoord Coord
shortest := MaxInt
shortestSteps := MaxInt
for p1i, p1 := range allWires[0].path {
if p1.x == 0 && p1.y == 0 {
continue
}
for p2i, p2 := range allWires[1].path {
if p2.x == 0 && p2.y == 0 {
continue
}
if p1.equals(p2) {
wrk := manhattanDistance(p1.x, p1.y, 0, 0)
if wrk < shortest {
shortest = wrk
shortestCoord = p1
}
if p1i+p2i < shortestSteps {
shortestSteps = p1i + p2i
fewestStepsCoord = p1
}
}
}
}
fmt.Println("Closest:", shortest, shortestCoord)
fmt.Println("Fewest Steps:", shortestSteps, fewestStepsCoord)
}
type Wire struct {
curr Coord
path []Coord
}
func NewWire() *Wire {
w := Wire{}
w.curr = Coord{0, 0}
w.path = append(w.path, w.curr)
return &w
}
func (w *Wire) Go(cmd string) {
dir := cmd[0]
length := Atoi(cmd[1:])
for length > 0 {
w.Move(dir)
w.path = append(w.path, w.curr)
length--
}
}
func (w *Wire) Move(dir byte) {
switch dir {
case 'U':
w.curr = Coord{w.curr.x, w.curr.y - 1}
case 'R':
w.curr = Coord{w.curr.x + 1, w.curr.y}
case 'D':
w.curr = Coord{w.curr.x, w.curr.y + 1}
case 'L':
w.curr = Coord{w.curr.x - 1, w.curr.y}
}
}
type Coord struct {
x, y int
}
func (c Coord) equals(b Coord) bool {
return c.x == b.x && c.y == b.y
}
func (c Coord) string() string {
return fmt.Sprintf("{%2d,%2d}", c.x, c.y)
}
func manhattanDistance(x1, y1, x2, y2 int) int {
return int(math.Abs(float64(x1)-float64(x2)) + math.Abs(float64(y1)-float64(y2)))
}
func StdinToStringSlice() []string {
var input []string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
input = append(input, scanner.Text())
}
return input
}
func Atoi(i string) int {
var ret int
var err error
if ret, err = strconv.Atoi(i); err != nil {
log.Fatal("Invalid Atoi")
}
return ret
}