day2.go (1498B)
- package main
- import (
- "fmt"
- "io/ioutil"
- "math"
- "os"
- "strconv"
- "strings"
- )
- func line_positions(line string) (positions [][2]int) {
- position := [2]int{0, 0} // (x,y)
- for _, move := range strings.Split(line, ",") {
- direction := strings.Split(move, "")[0]
- amount, err := strconv.Atoi(move[1:])
- if err != nil {
- fmt.Println(err)
- }
- for i := 0; i < amount; i++ {
- switch direction {
- case "U":
- position[0]++
- case "D":
- position[0]--
- case "L":
- position[1]++
- case "R":
- position[1]--
- }
- positions = append(positions, position)
- }
- }
- return
- }
- func main() {
- if len(os.Args) != 2 {
- fmt.Printf("Usage: %s [input file]\n", os.Args[0])
- os.Exit(1)
- }
- inputPath := os.Args[1]
- content, err := ioutil.ReadFile(inputPath)
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
- fileString := string(content)
- lines := strings.Split(fileString, "\n")
- line1 := line_positions(lines[0])
- line2 := line_positions(lines[1])
- var intercepts [][2]int
- for _, pos1 := range line1 {
- for _, pos2 := range line2 {
- if pos1 == pos2 {
- intercepts = append(intercepts, pos1)
- }
- }
- }
- fmt.Printf("%3d\n", intercepts)
- minDistance := float64(0)
- for _, intercept := range intercepts {
- var distance float64
- distance += math.Abs(float64(intercept[0]))
- distance += math.Abs(float64(intercept[1]))
- if minDistance == 0 {
- minDistance = distance
- } else {
- minDistance = math.Min(minDistance, distance)
- }
- }
- fmt.Println(minDistance)
- }