File tree Expand file tree Collapse file tree 1 file changed +29
-6
lines changed Expand file tree Collapse file tree 1 file changed +29
-6
lines changed Original file line number Diff line number Diff line change 2
2
3
3
class Day19 < Day # >
4
4
5
+ def initialize ( *args )
6
+ super
7
+ towels , designs = input . split ( "\n \n " )
8
+ @towel_patterns = towels . split ( ", " )
9
+ @desired_designs = designs . split ( "\n " )
10
+ @design_cache = Hash . new ( 0 )
11
+ end
12
+
5
13
# @example
6
14
# day.part1 #=> 6
7
- def part1
8
- towels , designs = input . split ( "\n \n " )
9
- towel_matcher = Regexp . new ( /\A (#{ towels . gsub ( ", " , "|" ) } )+\z / )
10
- desired_designs = designs . split ( "\n " )
11
- desired_designs . count { |pattern | pattern . match? ( towel_matcher ) }
12
- end
15
+ def part1
16
+ towel_matcher = Regexp . new ( /\A (#{ @towel_patterns . join ( "|" ) } )+\z / )
17
+ @desired_designs . count { |pattern | pattern . match? ( towel_matcher ) }
18
+ end
13
19
14
20
# @example
15
21
# day.part2 #=> 16
16
22
def part2
23
+ @desired_designs . inject ( 0 ) do |count , design |
24
+ count += ways_to_make_design ( design )
25
+ end
26
+ end
27
+
28
+ # @example
29
+ # day.ways_to_make_design("brwrr") #=> 2
30
+ # day.ways_to_make_design("bggr") #=> 1
31
+ # day.ways_to_make_design("gbbr") #=> 4
32
+ def ways_to_make_design ( design )
33
+ return @design_cache [ design ] if @design_cache [ design ] > 0
34
+ return 1 if design . empty?
35
+
36
+ @design_cache [ design ] =
37
+ @towel_patterns . reduce ( 0 ) { |ways , towel |
38
+ ways += design . end_with? ( towel ) ? ways_to_make_design ( design [ ..( -( towel . length +1 ) ) ] ) : 0
39
+ }
17
40
end
18
41
19
42
EXAMPLE_INPUT = File . read ( "../inputs/day19-example-input.txt" )
You can’t perform that action at this time.
0 commit comments