Skip to content

Commit

Permalink
Solution for 2024, day 17
Browse files Browse the repository at this point in the history
  • Loading branch information
lucianoq committed Dec 17, 2024
1 parent e957c4c commit d36c155
Show file tree
Hide file tree
Showing 4 changed files with 145 additions and 0 deletions.
19 changes: 19 additions & 0 deletions 2024/17/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
input:
http "https://adventofcode.com/2024/day/17/input" "Cookie:session=${AOC_SESSION};" >input

main1:
go build -o main1 main1.go common.go

main2:
go build -o main2 main2.go common.go

.PHONY: run1 run2 clean

run1: main1 input
./main1 <input

run2: main2 input
./main2 <input

clean:
rm -f main1 main2 input
80 changes: 80 additions & 0 deletions 2024/17/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package main

import (
"bufio"
"os"
"strconv"
"strings"
)

func parseInput() (int, int, int, []int) {
scanner := bufio.NewScanner(os.Stdin)

scanner.Scan()
a, _ := strconv.Atoi(strings.Fields(scanner.Text())[2])

scanner.Scan()
b, _ := strconv.Atoi(strings.Fields(scanner.Text())[2])

scanner.Scan()
c, _ := strconv.Atoi(strings.Fields(scanner.Text())[2])

scanner.Scan()

scanner.Scan()
var code []int
for _, s := range strings.Split(strings.Fields(scanner.Text())[1], ",") {
n, _ := strconv.Atoi(s)
code = append(code, n)
}
return a, b, c, code
}

func run(a, b, c int, code []int) []int {
output := make([]int, 0)

for ip := 0; ip < len(code); {
var (
op = code[ip]
arg = code[ip+1]
combo = 0
)

switch arg {
case 1, 2, 3:
combo = arg
case 4:
combo = a
case 5:
combo = b
case 6:
combo = c
}

switch op {
case 0: // adv
a >>= combo
case 1: // bxl
b ^= arg
case 2: // bst
b = combo % 8
case 3: // jnz
if a != 0 {
ip = arg
continue
}
case 4: // bxc
b ^= c
case 5: // out
output = append(output, combo%8)
case 6: // bdv
b = a >> combo
case 7: // cdv
c = a >> combo
}

ip += 2
}

return output
}
23 changes: 23 additions & 0 deletions 2024/17/main1.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package main

import (
"fmt"
"strconv"
"strings"
)

func main() {
a, b, c, code := parseInput()

output := run(a, b, c, code)

fmt.Println(strings.Join(toStr(output), ","))
}

func toStr(x []int) []string {
s := make([]string, len(x))
for i := 0; i < len(x); i++ {
s[i] = strconv.Itoa(x[i])
}
return s
}
23 changes: 23 additions & 0 deletions 2024/17/main2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package main

import (
"fmt"
"slices"
)

func main() {
_, b, c, code := parseInput()

a := 0
for i := len(code) - 1; i >= 0; i-- {
// make room for 3 bits by shifting to the left
a <<= 3

// check incrementally only the latest bits,
// until we find the right value
for !slices.Equal(run(a, b, c, code), code[i:]) {
a++
}
}
fmt.Println(a)
}

0 comments on commit d36c155

Please sign in to comment.