Created
December 13, 2015 09:26
-
-
Save wconrad/2e0dab86f6a6e0f0031f to your computer and use it in GitHub Desktop.
Advent of Code, day 13
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# http://adventofcode.com/day/13 | |
INPUT_PATTERN = /^(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+).$/ | |
@deltas = Hash[ | |
File.read("input").lines.map do |line| | |
raise line.inspect unless line =~ INPUT_PATTERN | |
person, sign, delta, neighbor = $~.captures | |
delta = Integer(delta) | |
delta *= -1 if sign == "lose" | |
[[person, neighbor], delta] | |
end | |
] | |
def people | |
@deltas.keys.flatten.uniq | |
end | |
def best_happiness_delta | |
people.permutation.map do |arrangement| | |
arrangement << arrangement.first | |
[arrangement, arrangement.reverse].flat_map do |a| | |
a.each_cons(2).map do |pair| | |
@deltas.fetch(pair) | |
end | |
end.reduce(&:+) | |
end.max | |
end | |
# part 1 | |
puts best_happiness_delta | |
# part2 | |
people.each do |person| | |
pair = [person, "Me"] | |
@deltas[pair] = 0 | |
@deltas[pair.reverse] = 0 | |
end | |
puts best_happiness_delta |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment