Skip to content

Commit a46707a

Browse files
committed
Day 4 Ruby solutions
1 parent 5ed31bf commit a46707a

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed

04-1.rb

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#!/usr/bin/env ruby
2+
3+
$haystack = File.read('04.input').lines.map(&:strip).map(&:chars)
4+
5+
def find_dir(needle, x, y, dx, dy)
6+
return true if needle.empty?
7+
return false if x < 0 or
8+
x >= $haystack[0].size or
9+
y < 0 or
10+
y >= $haystack.size
11+
return false unless $haystack[y][x] == needle[0]
12+
13+
find_dir(needle[1..], x + dx, y + dy, dx, dy)
14+
end
15+
16+
def find(x, y)
17+
needle = 'XMAS'
18+
19+
count = 0
20+
[-1, 0, 1].each do |dx|
21+
[-1, 0, 1].each do |dy|
22+
next if dx.zero? and dy.zero?
23+
24+
count += 1 if find_dir(needle, x, y, dx, dy)
25+
end
26+
end
27+
count
28+
end
29+
30+
count = 0
31+
$haystack.each_index do |y|
32+
$haystack[0].each_index do |x|
33+
count += find(x, y)
34+
end
35+
end
36+
37+
puts count

04-2.rb

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#!/usr/bin/env ruby
2+
3+
require 'numo/narray'
4+
5+
class Puzzle
6+
def initialize(input)
7+
@height = input.size
8+
@width = input[0].size
9+
@map = Numo::UInt8.zeros(@height, @width)
10+
@height.times do |y|
11+
@width.times do |x|
12+
@map[y, x] = input[y][x].codepoints[0]
13+
end
14+
end
15+
16+
mas = [
17+
'M.S'.codepoints,
18+
'.A.'.codepoints,
19+
'M.S'.codepoints
20+
]
21+
@mas_height = mas.size
22+
@mas_width = mas[0].size
23+
xmas = Numo::UInt8.zeros(3, 3)
24+
@mas_height.times do |y|
25+
@mas_width.times do |x|
26+
xmas[y, x] = mas[y][x]
27+
end
28+
end
29+
@xmases = [xmas, xmas.rot90(1), xmas.rot90(2), xmas.rot90(3)]
30+
end
31+
32+
def match?(y, x)
33+
@xmases.any? do |xmas|
34+
res = true
35+
@mas_height.times do |my|
36+
@mas_width.times do |mx|
37+
next if xmas[my, mx] == 46 # .
38+
39+
res = false if xmas[my, mx] != @map[y + my, x + mx]
40+
end
41+
end
42+
res
43+
end
44+
end
45+
46+
def count_matches
47+
count = 0
48+
(@height - @mas_height + 1).times do |y|
49+
(@width - @mas_width + 1).times do |x|
50+
count += 1 if match?(y, x)
51+
end
52+
end
53+
count
54+
end
55+
end
56+
57+
input = File.read('04.input').lines.map(&:strip)
58+
puzzle = Puzzle.new(input)
59+
puts puzzle.count_matches

0 commit comments

Comments
 (0)