Created
December 6, 2017 22:13
-
-
Save ndedic/e1c7bb0036be118eb20bbc1a75276c43 to your computer and use it in GitHub Desktop.
Advent Of Code, day 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package aoc18 | |
import ( | |
"io/ioutil" | |
"log" | |
"strconv" | |
"strings" | |
) | |
type Maze struct { | |
offsets []int | |
steps int | |
currentIdx int | |
} | |
func (m *Maze) Jump(increase func()) { | |
val := m.offsets[m.currentIdx] | |
increase() | |
m.currentIdx += val | |
m.steps++ | |
} | |
func (m *Maze) CanEscape() bool { | |
return m.currentIdx > len(m.offsets)-1 | |
} | |
func (m *Maze) Solve(increase func()) int { | |
for { | |
if m.CanEscape() { | |
return m.steps | |
} | |
m.Jump(increase) | |
} | |
} | |
func SolveFirstPart(fileName string) int { | |
input := string(OpenFile(fileName)) | |
offsets := adaptInput(input) | |
maze := Maze{offsets, 0, 0} | |
return maze.Solve(func() { | |
maze.offsets[maze.currentIdx]++ | |
}) | |
} | |
func SolveSecondPart(fileName string) int { | |
input := string(OpenFile(fileName)) | |
maze := Maze{adaptInput(input), 0, 0} | |
return maze.Solve(func() { | |
val := maze.offsets[maze.currentIdx] | |
if val >= 3 { | |
maze.offsets[maze.currentIdx]-- | |
} else { | |
maze.offsets[maze.currentIdx]++ | |
} | |
}) | |
} | |
func adaptInput(input string) []int { | |
input = strings.Replace(input, "\r", "", -1) | |
arr := strings.Split(input, "\n") | |
offsets := []int{} | |
for _, val := range arr { | |
intVal, _ := strconv.Atoi(val) | |
offsets = append(offsets, intVal) | |
} | |
return offsets | |
} | |
func OpenFile(fileName string) []byte { | |
file, err := ioutil.ReadFile(fileName) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return file | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment