Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions days/day-08/solutions/tholok97.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package main

import (
"bufio"
"fmt"
"os"
"regexp"
"strconv"
)

type instruction struct {
arg int
op string
}
Comment on lines +11 to +14
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fun!


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

instructions := make([]instruction, 0)

for scanner.Scan() {
line := scanner.Text()

re := regexp.MustCompile(`^(nop|acc|jmp) ([+-]\d+)$`)
matches := re.FindStringSubmatch(line)

arg, err := strconv.Atoi(matches[2])

if err != nil {
panic("Misbehaving number")
}

instructions = append(instructions, instruction{
op: matches[1],
arg: arg,
})
}

_, accumulator := run(instructions)

fmt.Println(accumulator)

for i := 0; i < len(instructions); i++ {
swap := instructions[i].op

switch swap {
case "jmp":
instructions[i].op = "nop"
case "nop":
instructions[i].op = "jmp"
default:
continue
}

isInfinite, accumulator := run(instructions)

if !isInfinite {
fmt.Println(accumulator)
break
}

instructions[i].op = swap
}
}

func run(instructions []instruction) (isinfinite bool, accumulator int) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean 💯 😃

curr := 0

visited := make([]bool, len(instructions))

for {
if curr == len(instructions) {
return false, accumulator
}

if visited[curr] {
return true, accumulator
}

visited[curr] = true

ins := instructions[curr]

switch ins.op {
case "acc":
accumulator += ins.arg
curr++
case "nop":
curr++
case "jmp":
curr += ins.arg
}
}
}
1 change: 1 addition & 0 deletions days/day-08/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ D=$(dirname $(realpath $0))

echo ""
echo "--- Day 8: Handheld Halting ---"
$D/../../languages/go.sh $D/input.txt $D/output.txt $D/solutions/tholok97.go
$D/../../languages/sml.sh $D/input.txt $D/output.txt $D/solutions/day08.sml
$D/../../languages/deno.sh $D/input.txt $D/output.txt $D/solutions/day08.ts
echo ""