adventofcode/2017/day13/day13.go

99 lines
1.6 KiB
Go
Raw Permalink Normal View History

2017-12-13 14:00:00 +00:00
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
}