Skip to content

Instantly share code, notes, and snippets.

@daz-codes
Created December 2, 2024 11:23
Show Gist options
  • Save daz-codes/d5077b6d84b2a0eb7e596e1759dc9708 to your computer and use it in GitHub Desktop.
Save daz-codes/d5077b6d84b2a0eb7e596e1759dc9708 to your computer and use it in GitHub Desktop.
Advent of Code day 1
class LocationData
attr_reader :list, :left, :right, :ordered_list
def initialize(data)
@list = parse(data)
@left,@right = @list.transpose.map { |arr| arr.map(&:to_i).sort }
@ordered_list = [@left,@right].transpose
end
def total_distance
@ordered_list.map{ |pair| distance(*pair) }.sum
end
def total_similarity
@left.map{ |x| similarity(x) }.sum
end
private
def distance(x,y)
(x - y).abs
end
def similarity value
value * right_count(value)
end
def right_count value
@right.tally[value] || 0
end
def parse data
data.split("\n").map { |x| x.split(" ") }
end
end
location_list = LocationData.new(DATA.read)
puts "Total Distance: #{location_list.total_distance}"
puts "Similarity Socre: #{location_list.total_similarity}"
__END__
3 4
4 3
2 5
1 3
3 9
3 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment