diff --git a/MasterMindGame.java b/MasterMindGame.java index 508560c..707c3d0 100644 --- a/MasterMindGame.java +++ b/MasterMindGame.java @@ -1,4 +1,5 @@ import java.util.Optional; +import java.util.*; /** * A code-breaking game where the app selects a sequence of symbols, and @@ -22,3 +23,18 @@ public Optional play() { return Optional.empty(); } } + +class CodeGenerator { + public static String generateCode() { + Random random = new Random(); + String numbers = "0123456789"; + String code = ""; + + for (int i=0; i < 4; i++) { + int index = random.nextInt(numbers.length()); + code = code + numbers.charAt(index); + } + + return code; + } + } diff --git a/MasterMindGameTest.java b/MasterMindGameTest.java new file mode 100644 index 0000000..f8f672a --- /dev/null +++ b/MasterMindGameTest.java @@ -0,0 +1,45 @@ +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.*; +import java.util.regex.*; + +public class MasterMindGameTest { + + private static final String SYMBOLS = "0123456789"; + private static final Pattern CODE_PATTERN = + Pattern.compile("[" + Pattern.quote(SYMBOLS) + "]{4}"); + + +@Test +void isExactlyFourSymbols() { + + String code = CodeGenerator.generateCode(); + assertEquals(4, code.length(), "Code should be 4 symbol long"); + +} + +@Test +void areFromSymbolSet() { + + String code = CodeGenerator.generateCode(); + assertTrue(CODE_PATTERN.matcher(code).matches(), "Code must be from this symbol set: " + SYMBOLS); + +} + +@Test +void isNotMoreThanTwiceTheSize() { + + Map counts = new HashMap<>(); + int sampleSize = 100; + + for (int i = 0; i < sampleSize; i++) { + String code = CodeGenerator.generateCode(); + counts.merge(code, 1, Integer::sum); + } + + counts.forEach((code, count) -> + assertTrue(count <= 2, "Code '" + code + "' appeared " + count + " times")); +} + +} \ No newline at end of file