Skip to content

Commit 59e2ac0

Browse files
committed
day 5
Fun with sorting.
1 parent 39d592c commit 59e2ac0

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

2024/ruby/day05.rb

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
require_relative 'day'
2+
3+
class Day05 < Day # >
4+
5+
# @example
6+
# day.part1 #=> 143
7+
def part1
8+
updates
9+
.select { correct_order? _1 }
10+
.map { |update| update[ (update.length/2).ceil ] }
11+
.reduce(&:+)
12+
end
13+
14+
# @example
15+
# day.part2 #=> 123
16+
def part2
17+
updates
18+
.reject { correct_order? _1 }
19+
.map { |update| fix(update)[ (update.length/2).ceil ] }
20+
.reduce(&:+)
21+
end
22+
23+
# @example first
24+
# day.correct_order?([75,47,61,53,29]) #=> true
25+
# @example fourth
26+
# day.correct_order?([75,97,47,61,53]) #=> false
27+
def correct_order?(update)
28+
update
29+
.each_with_index { |page, idx|
30+
return false if rules[page].intersect?(update[0..idx])
31+
}
32+
true
33+
end
34+
35+
# @example fourth
36+
# day.fix([75,97,47,61,53]) #=> [97,75,47,61,53]
37+
# @example fifth
38+
# day.fix([61,13,29]) #=> [61,29,13]
39+
# @example last
40+
# day.fix([97,13,75,29,47]) #=> [97,75,47,29,13]
41+
def fix(update)
42+
update.sort { |x,y| rules[x].include?(y) ? -1 : 1 }
43+
end
44+
45+
def rules
46+
@rules ||=
47+
input
48+
.split("\n\n")[0]
49+
.split("\n")
50+
.each_with_object(Hash.new {|h,k| h[k]=[]}) { |line, rules_hash|
51+
x, y = line.split("|").map(&:to_i)
52+
rules_hash[x].append(y)
53+
}
54+
end
55+
56+
def updates
57+
@updates ||=
58+
input
59+
.split("\n\n")[1]
60+
.split("\n")
61+
.map { |line| line.split(",").map(&:to_i) }
62+
end
63+
64+
EXAMPLE_INPUT = File.read("../inputs/day05-example-input.txt")
65+
end

0 commit comments

Comments
 (0)