diff --git a/2022/README.md b/2022/README.md index e88fb8bceb79a46a04340e98d954cb896e93eb0a..d35366ef4ea61ae8aff25369c5ee5f04bfee848e 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 9646d898ac8b6c4f1d1fd0264051c45ea0b33cf4..ed06688120fa08ec5b81ba74dd37274c76baeccc 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' -> {