Skip to content

Commit 4e48e96

Browse files
author
Robb Kidd
committed
2022 day 2 part 2 - a goodbye to structs
1 parent 4dfef48 commit 4e48e96

File tree

1 file changed

+45
-5
lines changed

1 file changed

+45
-5
lines changed

2022/ruby/day02.rb

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,58 @@ def part1
1515
@input
1616
.split("\n")
1717
.map { |line|
18-
score_round(line)
18+
score_round_part1(line)
1919
}
2020
.reduce(&:+)
2121
end
2222

23+
# @example
24+
# day.part2 #=> 12
2325
def part2
26+
@input
27+
.split("\n")
28+
.map { |line|
29+
score_round_part2(line)
30+
}
31+
.reduce(&:+)
2432
end
2533

2634
# @example
27-
# day.score_round('A Y') #=> 8
28-
def score_round(line)
35+
# day.score_round_part1('A Y') #=> 8
36+
# @example
37+
# day.score_round_part1('B X') #=> 1
38+
# @example
39+
# day.score_round_part1('C Z') #=> 6
40+
def score_round_part1(line)
2941
opp_choice, my_choice = line.split(" ")
3042
opp_shape = OPPONENT_MAP.fetch(opp_choice)
31-
my_shape = MY_MAP.fetch(my_choice)
43+
my_shape = PART1_MAP.fetch(my_choice)
3244

3345
SHAPE_SCORES.fetch(my_shape) + OUTCOME_SCORES.fetch(against(opp_shape, my_shape))
3446
end
3547

48+
# @example
49+
# day.score_round_part2('A Y') #=> 4
50+
# @example
51+
# day.score_round_part2('B X') #=> 1
52+
# @example
53+
# day.score_round_part2('C Z') #=> 7
54+
def score_round_part2(line)
55+
opp_choice, round_end = line.split(" ")
56+
opp_shape = OPPONENT_MAP.fetch(opp_choice)
57+
target_outcome = PART2_MAP.fetch(round_end)
58+
my_shape = case target_outcome
59+
when :draw
60+
opp_shape
61+
when :win
62+
DEFEATED_BY.fetch(opp_shape)
63+
when :lose
64+
DEFEATS.fetch(opp_shape)
65+
end
66+
67+
SHAPE_SCORES.fetch(my_shape) + OUTCOME_SCORES.fetch(target_outcome)
68+
end
69+
3670
def against(opp_shape, my_shape)
3771
return :draw if opp_shape == my_shape
3872
return :win if opp_shape == DEFEATS.fetch(my_shape)
@@ -53,12 +87,18 @@ def against(opp_shape, my_shape)
5387
'C' => :scissors,
5488
}
5589

56-
MY_MAP = {
90+
PART1_MAP = {
5791
'X' => :rock,
5892
'Y' => :paper,
5993
'Z' => :scissors,
6094
}
6195

96+
PART2_MAP = {
97+
'X' => :lose,
98+
'Y' => :draw,
99+
'Z' => :win,
100+
}
101+
62102
SHAPE_SCORES = {
63103
rock: 1,
64104
paper: 2,

0 commit comments

Comments
 (0)