Skip to content

Commit 81591a9

Browse files
committed
feat: add 2024 day 19 solution
1 parent e31e934 commit 81591a9

File tree

2 files changed

+107
-0
lines changed

2 files changed

+107
-0
lines changed

2024/19/dy-tea.v

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import os
2+
3+
const input_file := towels.input
4+
5+
fn possible(towels []string, current string, query string, mut visited map[string]bool) bool {
6+
if current == query {
7+
return true
8+
}
9+
10+
if current.len >= query.len {
11+
return false
12+
}
13+
14+
if visited[current] {
15+
return false
16+
}
17+
18+
visited[current] = true
19+
20+
for towel in towels {
21+
n := current + towel
22+
23+
if query == n {
24+
return true
25+
}
26+
27+
if query.starts_with(n) {
28+
if possible(towels, n, query, mut visited) {
29+
return true
30+
}
31+
}
32+
}
33+
34+
return false
35+
}
36+
37+
fn count_combinations(towels []string, current string, query string, mut visited map[string]u64) u64 {
38+
if current == query {
39+
return 1
40+
}
41+
42+
if current.len >= query.len {
43+
return 0
44+
}
45+
46+
if current in visited {
47+
return visited[current]
48+
}
49+
50+
mut sum := u64(0)
51+
52+
for towel in towels {
53+
n := current + towel
54+
55+
if query.starts_with(n) {
56+
sum += count_combinations(towels, n, query, mut visited)
57+
}
58+
}
59+
60+
visited[current] = sum
61+
return sum
62+
}
63+
64+
fn p1(input string) ! {
65+
lines := os.read_lines(input)!
66+
67+
towels := lines[0].split(', ')
68+
queries := lines[2..]
69+
70+
mut sum := 0
71+
for query in queries {
72+
mut visited := map[string]bool{}
73+
sum += if possible(towels, '', query, mut visited) { 1 } else { 0 }
74+
}
75+
76+
println(sum)
77+
}
78+
79+
fn p2(input string) ! {
80+
lines := os.read_lines(input)!
81+
82+
towels := lines[0].split(', ')
83+
queries := lines[2..]
84+
85+
mut sum := u64(0)
86+
for query in queries {
87+
mut visited := map[string]u64{}
88+
sum += count_combinations(towels, '', query, mut visited)
89+
}
90+
91+
println(sum)
92+
}
93+
94+
fn main() {
95+
p1(input_file)!
96+
p2(input_file)!
97+
}

2024/19/towels.input

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
r, wr, b, g, bwu, rb, gb, br
2+
3+
brwrr
4+
bggr
5+
gbbr
6+
rrbgbr
7+
ubwu
8+
bwurrg
9+
brgr
10+
bbrgwb

0 commit comments

Comments
 (0)