From 6185736ef64078a94efcb13d2fad168fe01be6ac Mon Sep 17 00:00:00 2001 From: Anna Wiggins Date: Wed, 5 Dec 2018 04:04:53 -0500 Subject: [PATCH] Day 5, part 2. --- 2018/day05-2.go | 27 +++++++++++++++++++++++++++ 2018/internal/polymer/polymer.go | 16 ++++++++++++++-- 2 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 2018/day05-2.go diff --git a/2018/day05-2.go b/2018/day05-2.go new file mode 100644 index 0000000..d3774f6 --- /dev/null +++ b/2018/day05-2.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + + "internal/polymer" + "internal/util" +) + +func main() { + data := util.ReadInputBytes() + result := [26][]byte{} + + for i := 0; i < 26; i++ { + result[i] = polymer.StripElement(data, rune('a'+i)) + result[i] = polymer.ApplyReactions(result[i]) + } + + shortest := len(result[0]) + for i := 1; i < 26; i++ { + if len(result[i]) < shortest { + shortest = len(result[i]) + } + } + + fmt.Println(shortest) +} diff --git a/2018/internal/polymer/polymer.go b/2018/internal/polymer/polymer.go index 1ed77bd..2d949e8 100644 --- a/2018/internal/polymer/polymer.go +++ b/2018/internal/polymer/polymer.go @@ -3,9 +3,10 @@ package polymer import ( "bytes" + "unicode" ) -func ApplyReactions(data []byte) string { +func ApplyReactions(data []byte) []byte { result := data changed := true @@ -13,7 +14,7 @@ func ApplyReactions(data []byte) string { result, changed = React(result) } - return string(result) + return result } // React finds substrings of the form "xX" or "Xx" and removes them, returning @@ -40,3 +41,14 @@ func React(data []byte) ([]byte, bool) { // No changes possible. return result.Bytes(), changed } + +// StripElement removes all instances of letter or its upper-case counterpart +// from the input. +func StripElement(data []byte, strip rune) []byte { + return bytes.Map(func(r rune) rune { + if r == strip || r == unicode.ToUpper(strip) { + return -1 + } + return r + }, data) +}