diff --git a/2017/day13/day13.go b/2017/day13/day13.go new file mode 100644 index 0000000..c050105 --- /dev/null +++ b/2017/day13/day13.go @@ -0,0 +1,98 @@ +package main + +import ( + "bufio" + "fmt" + "log" + "math" + "os" + "strconv" + "strings" +) + +var lyrs map[int]int + +func main() { + inp := StdinToStrings() + lyrs = make(map[int]int) + for i := range inp { + pts := strings.Split(inp[i], ":") + lyrs[Atoi(pts[0])] = Atoi(strings.TrimSpace(pts[1])) + } + fmt.Println("== Part 1 ==") + fmt.Println("Total Severity:", HitchARide(0, false)) + + fmt.Println("== Part 2 ==") + fmt.Println("Delay", FindNoSeverity(), "picoseconds") +} + +func HitchARide(delay int, brk bool) int { + var tm, top, sev int + for k := range lyrs { + if k > top { + top = k + } + } + for tm = delay; tm <= (top + delay); tm++ { + if v, ok := lyrs[(tm - delay)]; ok { + // There is a scanner here, did it see us? + if FindPos2(tm, v) == 0 { + sev += (tm * v) + if brk { + return -1 + } + } + } + } + return sev +} + +func FindNoSeverity() int { + maxInt := int((^uint(0) >> 1)) + for i := 0; i < maxInt; i++ { + if HitchARide(i, true) == 0 { + return i + } + } + return -1 +} + +func FindPos(tm, lngth int) int { + var ret int + var isAsc bool + for i := tm; i > 0; i-- { + if ret == lngth-1 || ret == 0 { + isAsc = !isAsc + } + if isAsc { + ret++ + } else { + ret-- + } + } + return ret +} + +func FindPos2(tm, lngth int) int { + loop := (lngth - 1) * 2 + pos := (lngth - 1) - int(math.Abs(float64((lngth-1)-(tm%loop)))) + return pos +} + +func StdinToStrings() []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 +} diff --git a/2017/day13/input b/2017/day13/input new file mode 100644 index 0000000..b53d9ed --- /dev/null +++ b/2017/day13/input @@ -0,0 +1,44 @@ +0: 3 +1: 2 +2: 5 +4: 4 +6: 4 +8: 6 +10: 6 +12: 6 +14: 8 +16: 6 +18: 8 +20: 8 +22: 8 +24: 12 +26: 8 +28: 12 +30: 8 +32: 12 +34: 12 +36: 14 +38: 10 +40: 12 +42: 14 +44: 10 +46: 14 +48: 12 +50: 14 +52: 12 +54: 9 +56: 14 +58: 12 +60: 12 +64: 14 +66: 12 +70: 14 +76: 20 +78: 17 +80: 14 +84: 14 +86: 14 +88: 18 +90: 20 +92: 14 +98: 18 diff --git a/2017/day13/testinput b/2017/day13/testinput new file mode 100644 index 0000000..0239024 --- /dev/null +++ b/2017/day13/testinput @@ -0,0 +1,4 @@ +0: 3 +1: 2 +4: 4 +6: 4