1
0
Fork 0
advent-of-code-2024/04/4-1.rb

124 lines
2.5 KiB
Ruby
Raw Normal View History

2024-12-05 22:58:54 -05:00
#!/usr/bin/env ruby
problem = 4
@input = File.readlines("#{problem}.input").map { _1.chomp.chars }.reject { _1.empty? }
#@input = DATA.read.split("\n").map(&:chars)
def diagnal?(x, y, dx, dy)
if dx == -1 && dy == -1
return false unless x >= 3 && y >= 3
return @input[y][x] + @input[y-1][x-1] + @input[y-2][x-2] + @input[y-3][x-3] == "XMAS"
elsif dx == -1 && dy == 1
return false unless x >= 3 && y <= @input.size - 4
return @input[y][x] + @input[y+1][x-1] + @input[y+2][x-2] + @input[y+3][x-3] == "XMAS"
elsif dx = 1 && dy == -1
return false unless x <= @input.first.size - 4 && y >= 3
return @input[y][x] + @input[y-1][x+1] + @input[y-2][x+2] + @input[y-3][x+3] == "XMAS"
#elsif dx == 1 && dy == 1 -- SHRUG
else
return false unless x <= @input.first.size - 4 && y <= @input.size - 4
return @input[y][x] + @input[y+1][x+1] + @input[y+2][x+2] + @input[y+3][x+3] == "XMAS"
end
end
def horizontal?(x, y, dx)
row = @input[y]
if dx == -1
return false unless x >= 3
return row[x] + row[x-1] + row[x-2] + row[x-3] == "XMAS"
end
if dx == 1
return false unless x <= @input.first.size - 4
return row[x] + row[x+1] + row[x+2] + row[x+3] == "XMAS"
end
end
def vertical?(x, y, dy)
col = @input.transpose[x]
if dy == -1
return false unless y >= 3
return col[y] + col[y-1] + col[y-2] + col[y-3] == "XMAS"
end
if dy == 1
return false unless y <= @input.size - 4
return col[y] + col[y+1] + col[y+2] + col[y+3] == "XMAS"
end
end
xmas = 0
h = 0
d = 0
v = 0
puts "Scanning"
puts " - x: #{@input.first.size}"
puts " - y: #{@input.size}"
(0...@input.size).each do |y|
(0...@input.first.size) .each do |x|
next unless @input[y][x] == "X"
if diagnal?(x, y, -1, -1)
xmas += 1
d += 1
puts "Diag LU at #{x}, #{y}"
end
if diagnal?(x, y, 1, -1)
xmas += 1
d += 1
puts "Diag RU at #{x}, #{y}"
end
if diagnal?(x, y, -1, 1)
xmas += 1
d += 1
puts "Diag LD at #{x}, #{y}"
end
if diagnal?(x, y, 1, 1)
xmas += 1
d += 1
puts "Diag RD at #{x}, #{y}"
end
if horizontal?(x, y, -1)
xmas += 1
h += 1
end
if horizontal?(x, y, 1)
xmas += 1
h += 1
end
if vertical?(x, y, -1)
xmas += 1
v += 1
end
if vertical?(x, y, 1)
xmas += 1
v += 1
end
end
end
puts "Diag: #{d}"
puts "Hor: #{h}"
puts "Vert: #{v}"
p xmas
__END__
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX