Skip to content

Instantly share code, notes, and snippets.

@andrewzah
Created December 3, 2023 09:01
Show Gist options
  • Save andrewzah/d1c658e14ebf578377c7af99abc7ce9c to your computer and use it in GitHub Desktop.
Save andrewzah/d1c658e14ebf578377c7af99abc7ce9c to your computer and use it in GitHub Desktop.
advent of code 2023 - day 3
lines = File
.readlines("input.txt")
.map{|l| l.strip }
@arr_length_bound = lines.length - 1
@arr_width_bound = lines[0].chars.length - 1
@array = lines.map{|l| l.chars}
@valid_nums = []
@nums = %w[1 2 3 4 5 6 7 8 9 0]
def valid_coordinate?(i, j)
if i < 0 || j < 0 || i > @arr_length_bound || j > @arr_width_bound
false
else
true
end
end
def touching_symbol?(i, j)
neighbors = [
[i-1, j-1],
[i-1, j],
[i-1, j+1],
[i, j-1],
[i, j+1],
[i+1, j-1],
[i+1, j],
[i+1, j+1],
].filter{|i, j| valid_coordinate?(i, j)}
.map{|i, j|
@array[i][j]
}
pp neighbors
neighbors = neighbors
.filter{|e| e != "." }
.filter{|e| [email protected]?(e) }
neighbors.length > 0
end
curr_num = ""
touching = false
@array.each_with_index do |sub_array, i|
@valid_nums << curr_num.to_i if curr_num != "" && touching == true
curr_num = ""
touching = false
sub_array.each_with_index do |item, j|
if @nums.include?(item)
curr_num << item
touching = true if touching_symbol?(i, j)
else
@valid_nums << curr_num.to_i if curr_num != "" && touching == true
curr_num = ""
touching = false
next
end
end
end
pp @valid_nums.sum
lines = File
.readlines("input.txt")
.map{|l| l.strip }
@nums = %w[1 2 3 4 5 6 7 8 9 0]
@arr_length_bound = lines.length - 1
@arr_width_bound = lines[0].chars.length - 1
@array = lines.map{|l| l.chars}
def valid_coordinate?(i, j)
if i < 0 || j < 0 || i > @arr_length_bound || j > @arr_width_bound
false
else
true
end
end
def touching_symbol?(i, j)
neighbors = [
[i-1, j-1],
[i-1, j],
[i-1, j+1],
[i, j-1],
[i, j+1],
[i+1, j-1],
[i+1, j],
[i+1, j+1],
].filter{|i, j| valid_coordinate?(i, j)}
.map{|i, j|
[@array[i][j], [i, j]]
}
.filter{|(k, v)| k == "*" }
.flatten
# disambiguate symbols
if neighbors.length > 0
symbol = "#{neighbors[0]}-#{neighbors[1]}-#{neighbors[2]}"
@last_symbol = symbol
end
neighbors.length > 0
end
curr_num = ""
touching = false
@last_symbol = ""
@valid_nums = []
@array.each_with_index do |sub_array, i|
@valid_nums << [curr_num.to_i, @last_symbol] if curr_num != "" && touching == true
curr_num = ""
touching = false
sub_array.each_with_index do |item, j|
if @nums.include?(item)
curr_num << item
touching = true if touching_symbol?(i, j)
else
@valid_nums << [curr_num.to_i, @last_symbol] if curr_num != "" && touching == true
curr_num = ""
touching = false
next
end
end
end
@h = Hash.new
@valid_nums.each do |k, v|
if @h.key?(v)
@h[v] << k
else
@h[v] = [k]
end
end
p @h.filter{|k, v| v.length == 2}.map{|k, v| v.reduce(:*)}.sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment