day 8 part 2

master
Araozu 2024-04-25 18:05:20 -05:00
parent 650002f27f
commit e869fc2152
2 changed files with 63 additions and 1 deletions

View File

@ -29,7 +29,7 @@ func main() {
runAndBenchmark("07", "2", false, solutions.Day07Part02) runAndBenchmark("07", "2", false, solutions.Day07Part02)
runAndBenchmark("08", "1", false, solutions.Day08Part01) runAndBenchmark("08", "1", false, solutions.Day08Part01)
runAndBenchmark("08", "2", true, solutions.Day08Part02) runAndBenchmark("08", "2", false, solutions.Day08Part02)
} }
type execute func(bool) int type execute func(bool) int

View File

@ -86,5 +86,67 @@ func Day08Part01(isTest bool) int {
} }
func Day08Part02(isTest bool) int { func Day08Part02(isTest bool) int {
input := ReadInput("08", isTest)
groups := strings.Split(input, "\n")
instructionArray := make([]*InstructionStore, len(groups))
for idx, line := range groups {
instr, value := parseInstruction(line)
instructionArray[idx] = &InstructionStore{instruction: instr, value: value, executionCount: 0}
}
for currentExecutionCount := 0; currentExecutionCount < len(instructionArray); currentExecutionCount += 1 {
accumulator := 0
instructionPointer := 0
jmpNopCount := 0
for {
// success condition
if instructionPointer == len(instructionArray) {
return accumulator
}
currentInstruction := instructionArray[instructionPointer]
inst := currentInstruction.instruction
value := currentInstruction.value
executionCount := currentInstruction.executionCount
// If a loop is detected, break this loop
if executionCount == currentExecutionCount+1 {
break
}
// Check if the intruction is jmp or not, if it's the nth such instr, and change them if so)
if inst == nop || inst == jmp {
if jmpNopCount == currentExecutionCount {
// switch jmp & nop
if inst == nop {
inst = jmp
} else if inst == jmp {
inst = nop
}
}
jmpNopCount += 1
}
switch inst {
case nop:
currentInstruction.executionCount = currentExecutionCount + 1
instructionPointer += 1
case acc:
currentInstruction.executionCount = currentExecutionCount + 1
accumulator += value
instructionPointer += 1
case jmp:
currentInstruction.executionCount = currentExecutionCount + 1
instructionPointer += value
default:
panic("Found an invalid instruction while trying to execute it. " + strconv.Itoa(int(inst)))
}
}
}
return -1 return -1
} }