Refactor day 5 solution for working on part 2.
This commit is contained in:
parent
f2e2797587
commit
ec2c98f960
2018
|
@ -1,50 +1,14 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
|
||||
"internal/polymer"
|
||||
"internal/util"
|
||||
)
|
||||
|
||||
func main() {
|
||||
data := util.ReadInputBytes()
|
||||
result := ApplyReactions(data)
|
||||
result := polymer.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
|
||||
}
|
||||
|
|
42
2018/internal/polymer/polymer.go
Normal file
42
2018/internal/polymer/polymer.go
Normal file
|
@ -0,0 +1,42 @@
|
|||
// Functions for operating on polymers from day 5.
|
||||
package polymer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
)
|
||||
|
||||
func ApplyReactions(data []byte) string {
|
||||
result := data
|
||||
changed := true
|
||||
|
||||
for changed {
|
||||
result, changed = React(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
|
||||
}
|
Loading…
Reference in New Issue
Block a user