From f046204b9b2d62f8c22af14891bed8aa0e5fee05 Mon Sep 17 00:00:00 2001 From: Thomas Fabre <tfabre@takima.fr> Date: Fri, 23 Jun 2023 14:23:10 +0200 Subject: [PATCH] Refactor threeOfAKind with Roll --- src/main/java/io/takima/Yatzy.java | 24 ++++++++---------------- src/test/java/io/takima/YatzyTest.java | 10 +++++----- 2 files changed, 13 insertions(+), 21 deletions(-) diff --git a/src/main/java/io/takima/Yatzy.java b/src/main/java/io/takima/Yatzy.java index 0b594f0..d8b6f79 100644 --- a/src/main/java/io/takima/Yatzy.java +++ b/src/main/java/io/takima/Yatzy.java @@ -66,6 +66,14 @@ public final class Yatzy { return pairs.get(0) + pairs.get(1); } + public static int threeOfAKind(Roll roll) { + return roll.countByDiceValueStream() + .filter(entry -> entry.getValue() >= 3) + .max(Map.Entry.comparingByKey()) + .map(entry -> entry.getKey() * 3) + .orElse(0); + } + public static int fourOfAKind(Roll roll) { return roll.countByDiceValueStream() .filter(entry -> entry.getValue() >= 4) @@ -74,22 +82,6 @@ public final class Yatzy { .orElse(0); } - public static int threeOfAKind(int d1, int d2, int d3, int d4, int d5) { - int[] counts; - counts = new int[6]; - counts[d1 - 1]++; - counts[d2 - 1]++; - counts[d3 - 1]++; - counts[d4 - 1]++; - counts[d5 - 1]++; - for (int i = 0; i < 6; i++) { - if (counts[i] >= 3) { - return (i + 1) * 3; - } - } - return 0; - } - public static int smallStraight(int d1, int d2, int d3, int d4, int d5) { int[] counts; counts = new int[6]; diff --git a/src/test/java/io/takima/YatzyTest.java b/src/test/java/io/takima/YatzyTest.java index 18c9762..8c07f44 100644 --- a/src/test/java/io/takima/YatzyTest.java +++ b/src/test/java/io/takima/YatzyTest.java @@ -106,16 +106,16 @@ class YatzyTest { @Test void threeOfAKindShouldSumTheThreeDiceWithTheSameValue() { assertAll( - () -> assertEquals(9, Yatzy.threeOfAKind(3, 3, 3, 4, 5)), - () -> assertEquals(15, Yatzy.threeOfAKind(5, 3, 5, 4, 5)), - () -> assertEquals(9, Yatzy.threeOfAKind(3, 3, 3, 3, 5)), - () -> assertEquals(9, Yatzy.threeOfAKind(3, 3, 3, 3, 3)) + () -> assertEquals(9, Yatzy.threeOfAKind(roll(3, 3, 3, 4, 5))), + () -> assertEquals(15, Yatzy.threeOfAKind(roll(5, 3, 5, 4, 5))), + () -> assertEquals(9, Yatzy.threeOfAKind(roll(3, 3, 3, 3, 5))), + () -> assertEquals(9, Yatzy.threeOfAKind(roll(3, 3, 3, 3, 3))) ); } @Test void threeOfAKindShouldReturnZeroIfThereIsNoThreeDiceWithTheSameValue() { - assertEquals(0, Yatzy.threeOfAKind(3, 3, 4, 5, 6)); + assertEquals(0, Yatzy.threeOfAKind(roll(3, 3, 4, 5, 6))); } @Test -- GitLab