96 lines
1.5 KiB
Go
96 lines
1.5 KiB
Go
package day10
|
|
|
|
import (
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
type Solver struct {
|
|
ops []Op
|
|
}
|
|
|
|
type Op struct {
|
|
opcode string
|
|
operand int
|
|
}
|
|
|
|
func (s *Solver) ParseInput(input []string) {
|
|
s.ops = make([]Op, len(input))
|
|
|
|
for i, line := range input {
|
|
splits := strings.Split(line, " ")
|
|
opcode := splits[0]
|
|
switch opcode {
|
|
case "noop":
|
|
s.ops[i] = Op{opcode, 0}
|
|
case "addx":
|
|
operand, _ := strconv.Atoi(splits[1])
|
|
s.ops[i] = Op{opcode, operand}
|
|
}
|
|
}
|
|
}
|
|
|
|
const maxCycles = 220
|
|
|
|
func (s *Solver) SolvePart1() any {
|
|
cycleValuesForX := s.getXValues()
|
|
|
|
return getSignalStrength(cycleValuesForX)
|
|
}
|
|
|
|
func (s *Solver) getXValues() []int {
|
|
var cycleValuesForX = make([]int, 0)
|
|
X := 1
|
|
|
|
cycleNum := 0
|
|
|
|
for _, op := range s.ops {
|
|
switch op.opcode {
|
|
case "noop":
|
|
cycleValuesForX = append(cycleValuesForX, X)
|
|
cycleNum += 1
|
|
case "addx":
|
|
cycleValuesForX = append(cycleValuesForX, X, X)
|
|
cycleNum += 2
|
|
|
|
X += op.operand
|
|
}
|
|
}
|
|
|
|
for cycleNum <= 2*maxCycles {
|
|
cycleValuesForX = append(cycleValuesForX, X)
|
|
cycleNum++
|
|
}
|
|
return cycleValuesForX
|
|
}
|
|
|
|
func getSignalStrength(xValues []int) int {
|
|
const start = 20
|
|
const step = 40
|
|
|
|
var total int
|
|
for i := start; i <= maxCycles; i += step {
|
|
total += i * xValues[i-1]
|
|
}
|
|
return total
|
|
}
|
|
|
|
func (s *Solver) SolvePart2() any {
|
|
cycleValuesForX := s.getXValues()
|
|
|
|
for r := 0; r < 6; r++ {
|
|
for c := 0; c < 40; c++ {
|
|
cycle := 40*r + c
|
|
xValue := cycleValuesForX[cycle]
|
|
if c >= xValue-1 && c <= xValue+1 {
|
|
fmt.Print("#")
|
|
} else {
|
|
fmt.Print(" ")
|
|
}
|
|
}
|
|
fmt.Println()
|
|
}
|
|
return "RGLRBZAU"
|
|
}
|