Rename shared packages by day instead of vaguely by purpose.
This commit is contained in:
parent
42cb05ba7f
commit
31f60eca0e
22 changed files with 49 additions and 50 deletions
54
2018/internal/day05/polymer.go
Normal file
54
2018/internal/day05/polymer.go
Normal file
|
@ -0,0 +1,54 @@
|
|||
// Functions for operating on polymers from day 5.
|
||||
package day05
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
func ApplyReactions(data []byte) []byte {
|
||||
result := data
|
||||
changed := true
|
||||
|
||||
for changed {
|
||||
result, changed = React(result)
|
||||
}
|
||||
|
||||
return 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
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue