package main
import (
"bufio"
"log"
"os"
"strings"
)
type insert map[string]byte
type polimer struct {
template string
inserts insert
}
func main() {
if err := myMain(); err != nil {
log.Println(err)
}
}
func myMain() error {
p, err := parseInput("input.txt")
if err != nil {
return err
}
log.Println(solveFirst(p))
return nil
}
func solveFirst(p polimer) int {
tmp := strings.Builder{}
for i := 0; i < 10; i++ {
for ch := range p.template {
if ch == len(p.template)-1 {
tmp.WriteByte(p.template[ch])
break
}
tmp.WriteByte(p.template[ch])
tmp.WriteByte(p.inserts[p.template[ch:ch+2]])
}
p.template = tmp.String()
tmp.Reset()
}
chars := map[rune]int{}
for _, ch := range p.template {
chars[ch]++
}
var min, max int
for _, v := range chars {
if min == 0 {
min = v
}
if v > max {
max = v
}
if v < min {
min = v
}
}
return max - min
}
func parseInput(fileName string) (polimer, error) {
var ret = polimer{}
ret.inserts = insert{}
fd, err := os.Open(fileName)
if err != nil {
return ret, err
}
defer fd.Close()
buf := bufio.NewScanner(fd)
for buf.Scan() {
if buf.Text() == "" {
continue
}
tmp := strings.Split(buf.Text(), " -> ")
if len(tmp) == 2 {
ret.inserts[tmp[0]] = tmp[1][0]
} else { // polymer template
ret.template = tmp[0]
}
}
return ret, nil
}