From f2e2797587074633a7698c39aa7e0f3fda281c68 Mon Sep 17 00:00:00 2001 From: Anna Wiggins Date: Wed, 5 Dec 2018 03:49:03 -0500 Subject: [PATCH] Day 5, part 1. --- 2018/day05-1.go | 50 +++++++++++++++++++++++++++++++++++++ 2018/internal/util/input.go | 13 ++++++++++ 2 files changed, 63 insertions(+) create mode 100644 2018/day05-1.go diff --git a/2018/day05-1.go b/2018/day05-1.go new file mode 100644 index 0000000..ce3c281 --- /dev/null +++ b/2018/day05-1.go @@ -0,0 +1,50 @@ +package main + +import ( + "bytes" + "fmt" + + "internal/util" +) + +func main() { + data := util.ReadInputBytes() + result := ApplyReactions(data) + fmt.Println(len(result)) +} + +func ApplyReactions(data []byte) string { + result := data + changed := true + + for changed { + result, changed = React1(result) + } + + return string(result) +} + +// React finds substrings of the form "xX" or "Xx" and removes them, returning +// the resulting bytes. +func React(data []byte) ([]byte, bool) { + result := bytes.Buffer{} + changed := false + + for i := 0; i < len(data); i++ { + if i < len(data)-1 && + data[i] != data[i+1] && + string(bytes.ToLower([]byte{data[i]})) == string(bytes.ToLower([]byte{data[i+1]})) { + + // we've found a reduction; skip over it without writing + // return append(data[:i], data[i+2:]...), true + i++ + changed = true + continue + } + + result.WriteByte(data[i]) + } + + // No changes possible. + return result.Bytes(), changed +} diff --git a/2018/internal/util/input.go b/2018/internal/util/input.go index 21562a2..530f6a2 100644 --- a/2018/internal/util/input.go +++ b/2018/internal/util/input.go @@ -2,6 +2,8 @@ package util import ( "bufio" + "bytes" + "io/ioutil" "os" ) @@ -22,3 +24,14 @@ func ReadInput() []string { return lines } + +// ReadInputS is like ReadInput, but returns a byte array. +func ReadInputBytes() []byte { + rawData, err := ioutil.ReadFile(os.Args[1]) + + if err != nil { + panic(err) + } + + return bytes.TrimRight(rawData, "\n") +}