Day 5, part 1.
This commit is contained in:
parent
1615406a28
commit
f2e2797587
50
2018/day05-1.go
Normal file
50
2018/day05-1.go
Normal file
|
@ -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
|
||||||
|
}
|
|
@ -2,6 +2,8 @@ package util
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"io/ioutil"
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -22,3 +24,14 @@ func ReadInput() []string {
|
||||||
|
|
||||||
return lines
|
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")
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user