aboutsummaryrefslogtreecommitdiff
path: root/2021/14/second.go
blob: 06c6890bb5115a29e79fd2d129ca2936120b5a2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main

// TODO Off by one! I don't know where!!!!!
// I get  : 3459174981022
// I need : 3459174981021

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strings"
)

type transform struct {
	first  byte
	second byte
	res    byte
	count  int
}

type letter struct {
	value byte
	count int
}

var (
	pairs   []transform
	letters []letter
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)

	scanner.Scan()
	polymer := scanner.Text()
out:
	for i := 0; i < len(polymer); i++ {
		for j := range letters {
			if letters[j].value == polymer[i] {
				letters[j].count++
				continue out
			}
		}
		letters = append(letters, letter{polymer[i], 1})
	}
	scanner.Scan()

	for scanner.Scan() {
		line := strings.Split(scanner.Text(), " -> ")
		pairs = append(pairs, transform{line[0][0], line[0][1], line[1][0], 0})
	}
	for i := 0; i < len(polymer)-1; i++ {
		for j, v := range pairs {
			if v.first == polymer[i] && v.second == polymer[i+1] {
				pairs[j].count++
			}
		}
	}
	newPairs := make([]transform, len(pairs))
	copy(newPairs, pairs)
	for s := 1; s < 40; s++ {
		for j := range newPairs {
			newPairs[j].count = 0
		}
		for _, a := range pairs {
			if a.count > 0 {
				for j, b := range pairs {
					if b.first == a.first && b.second == a.res {
						newPairs[j].count += a.count
						break
					}
				}
				for j, b := range pairs {
					if b.first == a.res && b.second == a.second {
						newPairs[j].count += a.count
						break
					}
				}
			}
		}
		copy(pairs, newPairs)
	out2:
		for _, v := range pairs {
			for j := range letters {
				if letters[j].value == v.res {
					letters[j].count += v.count
					continue out2
				}
			}
			letters = append(letters, letter{v.res, v.count})
		}
	}
	sort.Slice(letters, func(i, j int) bool {
		return letters[i].count < letters[j].count
	})
	fmt.Println(letters[len(letters)-1].count - letters[0].count)
}