This commit is contained in:
2022-12-23 19:45:56 -08:00
commit 8792e5275a
77 changed files with 31154 additions and 0 deletions

98
solutions/day10/day10.go Normal file
View File

@@ -0,0 +1,98 @@
package day10
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func clearLine(line *[]rune) {
for idx := range *line {
(*line)[idx] = '.'
}
}
func printLine(line *[]rune) {
for _, c := range *line {
fmt.Printf("%c", c)
}
fmt.Println()
}
func registerCycle(cycle int, x int, line *[]rune) int {
result := 0
var position int
for position = cycle - 1; position > 40; position -= 40 {
}
if cycle == 20 || (cycle > 20 && ((cycle-20)%40 == 0)) {
result = x * cycle
//fmt.Println("register cycle", cycle, "value of x is", x, "signal strength is", result)
}
//if position == 0 {
// fmt.Println("position is", position, "and x is", x)
//}
if position >= x-1 && position <= x+1 {
(*line)[position] = '#'
}
if position == 40 {
printLine(line)
clearLine(line)
}
return result
}
func Run(filename string) {
file, err := os.Open(filename)
if err != nil {
fmt.Println("Error opening file:", err)
return
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
cycle := 1
x := 1
signalStrengthSum := 0
currentLine := []rune{'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'}
if len(currentLine) != 40 {
fmt.Println("line length", len(currentLine))
return
}
registerCycle(cycle, x, &currentLine)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "addx ") {
cycle += 1
signalStrengthSum += registerCycle(cycle, x, &currentLine)
cycle += 1
mod, err := strconv.Atoi(string(line[5:]))
if err != nil {
fmt.Println("Invalid x modifier", err, "having read", string(line[5:]))
return
}
x += mod
signalStrengthSum += registerCycle(cycle, x, &currentLine)
} else if strings.HasPrefix(line, "noop") {
cycle += 1
signalStrengthSum += registerCycle(cycle, x, &currentLine)
} else {
fmt.Println("PANIC: Unknown instruction:", line)
return
}
}
file.Close()
//printLine(line)
fmt.Println("Signal strength fun", signalStrengthSum)
}