From 15c834055523ad2560184b9494ddda3312d17500 Mon Sep 17 00:00:00 2001 From: Christopher Bohn <bohn@unl.edu> Date: Fri, 2 Dec 2022 08:06:43 -0600 Subject: [PATCH] Refactored Year 2022 Day 2 --- 2022/README.md | 5 ++++ .../java/edu/unl/cse/bohn/year2022/Day2.java | 23 ++++++++----------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/2022/README.md b/2022/README.md index e88fb8b..d35366e 100644 --- a/2022/README.md +++ b/2022/README.md @@ -39,6 +39,11 @@ The subproblems for both parts are Seems pretty straight-forward. +### Refactoring opportunity + +Parts 1 & 2 differ in whether we determine the outcome based off of "my" hand, or whether we determine "my" hand based off of the outcome. +Where we parameterized the commonality on Day 1, today we'll simply extract the commonality into a helper method. + ## Day 3 (coming soon) diff --git a/2022/src/main/java/edu/unl/cse/bohn/year2022/Day2.java b/2022/src/main/java/edu/unl/cse/bohn/year2022/Day2.java index 9646d89..ed06688 100644 --- a/2022/src/main/java/edu/unl/cse/bohn/year2022/Day2.java +++ b/2022/src/main/java/edu/unl/cse/bohn/year2022/Day2.java @@ -37,10 +37,7 @@ public class Day2 extends Puzzle { return totalScore; } - private long scoreOneRoundForPart1(String choices) { - long score; - Outcome outcome = Outcome.UNKNOWN; - //noinspection DuplicatedCode + private static Hand getOpponentHand(String choices) { Hand opponent = switch (choices.charAt(0)) { case 'A' -> Hand.ROCK; case 'B' -> Hand.PAPER; @@ -50,6 +47,13 @@ public class Day2 extends Puzzle { if (opponent == Hand.UNKNOWN) { throw new IllegalStateException("Opponent's hand determined as \"UNKNOWN\". Choices: { " + choices + " }"); } + return opponent; + } + + private long scoreOneRoundForPart1(String choices) { + long score; + Outcome outcome = Outcome.UNKNOWN; + Hand opponent = getOpponentHand(choices); Hand me; switch (choices.charAt(2)) { case 'X' -> { @@ -98,16 +102,7 @@ public class Day2 extends Puzzle { private long scoreOneRoundForPart2(String choices) { long score; // Outcome outcome = Outcome.UNKNOWN; - //noinspection DuplicatedCode - Hand opponent = switch (choices.charAt(0)) { - case 'A' -> Hand.ROCK; - case 'B' -> Hand.PAPER; - case 'C' -> Hand.SCISSORS; - default -> Hand.UNKNOWN; - }; - if (opponent == Hand.UNKNOWN) { - throw new IllegalStateException("Opponent's hand determined as \"UNKNOWN\". Choices: { " + choices + " }"); - } + Hand opponent = getOpponentHand(choices); Hand me; switch (choices.charAt(2)) { case 'X' -> { -- GitLab