Skip to content

Commit

Permalink
Solution for 2024, day 19
Browse files Browse the repository at this point in the history
  • Loading branch information
lucianoq committed Dec 19, 2024
1 parent c61d436 commit 0a347de
Show file tree
Hide file tree
Showing 5 changed files with 141 additions and 0 deletions.
20 changes: 20 additions & 0 deletions 2024/19/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
input:
http "https://adventofcode.com/2024/day/19/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

19 changes: 19 additions & 0 deletions 2024/19/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package main

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

func parseInput() ([]string, []string) {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
patterns := strings.Split(scanner.Text(), ", ")
scanner.Scan()
designs := make([]string, 0)
for scanner.Scan() {
designs = append(designs, scanner.Text())
}
return patterns, designs
}
43 changes: 43 additions & 0 deletions 2024/19/main1.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package main

import (
"fmt"
"strings"
)

func main() {
patterns, designs := parseInput()

cache := map[string]bool{}

sum := 0
for _, d := range designs {
if possible(d, patterns, cache) {
sum++
}
}
fmt.Println(sum)
}

func possible(d string, patterns []string, cache map[string]bool) bool {
if len(d) == 0 {
return true
}

if t, ok := cache[d]; ok {
return t
}

for _, p := range patterns {
if strings.HasPrefix(d, p) {
found := possible(d[len(p):], patterns, cache)
if found {
cache[d] = true
return true
}
}
}

cache[d] = false
return false
}
21 changes: 21 additions & 0 deletions 2024/19/main1_bad.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package main

import (
"fmt"
"regexp"
"strings"
)

func main() {
patterns, designs := parseInput()

rgxp := regexp.MustCompile(fmt.Sprintf("^(%s)+$", strings.Join(patterns, "|")))

sum := 0
for _, d := range designs {
if rgxp.MatchString(d) {
sum++
}
}
fmt.Println(sum)
}
38 changes: 38 additions & 0 deletions 2024/19/main2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import (
"fmt"
"strings"
)

func main() {
patterns, designs := parseInput()

cache := map[string]int{}

sum := 0
for _, d := range designs {
sum += ways(d, patterns, cache)
}
fmt.Println(sum)
}

func ways(d string, patterns []string, cache map[string]int) int {
if len(d) == 0 {
return 1
}

if w, ok := cache[d]; ok {
return w
}

w := 0
for _, p := range patterns {
if strings.HasPrefix(d, p) {
w += ways(d[len(p):], patterns, cache)
}
}

cache[d] = w
return w
}

0 comments on commit 0a347de

Please sign in to comment.