Skip to content

Instantly share code, notes, and snippets.

@wconrad
Last active December 9, 2015 12:15
Show Gist options
  • Select an option

  • Save wconrad/5ebb03be30772738654c to your computer and use it in GitHub Desktop.

Select an option

Save wconrad/5ebb03be30772738654c to your computer and use it in GitHub Desktop.
Advent of Code, day 9
#!/usr/bin/env ruby
# http://adventofcode.com/day/9
require "set"
class Map
attr_reader :cities
def initialize
@distances = {}
@cities = Set.new
end
def add(city1, city2, distance)
@distances[[city1, city2]] = distance
@distances[[city2, city1]] = distance
@cities << city1
@cities << city2
end
def distance_between(city_pair)
@distances.fetch(city_pair)
end
end
def parse_input
map = Map.new
File.read("input").each_line do |line|
raise unless line =~ /^(\w+) to (\w+) = (\d+)$/
city1, city2, distance = $~.captures
distance = Integer(distance)
map.add(city1, city2, distance)
end
map
end
def distance(route)
route.each_cons(2).map do |city_pair|
@map.distance_between(city_pair)
end.inject(&:+)
end
@map = parse_input
distances = @map.cities.to_a.permutation.map do |route|
distance(route)
end
puts distances.min
puts distances.max
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment