fork download
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.HashMap;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.Set;
  8.  
  9. class MasterMindPP {
  10.  
  11. public static Set<String> options = new HashSet<>();
  12.  
  13. // Load up permutations
  14. public static void loadPossibilities() {
  15. for (char c1 = 'a'; c1 <= 'z'; c1++) {
  16. for (char c2 = 'a'; c2 <= 'z'; c2++) {
  17. for (char c3 = 'a'; c3 <= 'z'; c3++) {
  18. for (char c4 = 'a'; c4 <= 'z'; c4++) {
  19. for (char c5 = 'a'; c5 <= 'z'; c5++) {
  20. options.add(c1 + "" + c2 + "" + c3 + "" + c4 + "" + c5);
  21. }
  22. }
  23. }
  24. }
  25. }
  26. System.out.println(options.size());
  27. }
  28.  
  29. // Remove all entries that do not yield the same score when matched with
  30. // guess / definite wrong anwers.
  31. public static void removeMatch(String guess, int score) {
  32. Set<String> remove = new HashSet<>();
  33. for (String entry : options) {
  34. int match = computeMatch(guess, entry);
  35. if (score != match)
  36. remove.add(entry);
  37. }
  38. options.removeAll(remove);
  39. }
  40.  
  41. // Given two strings, match them and return score 10*EXACT_MATCH +
  42. // MISMATCHES
  43. private static int computeMatch(String guess, String entry) {
  44. int exact = 0;
  45. int mismatch = 0;
  46. for (int i = 0; i < 5; i++) {
  47. if (guess.charAt(i) == entry.charAt(i))
  48. exact++;
  49. }
  50. Map<Character, Integer> mapG = mapIt(guess);
  51. Map<Character, Integer> mapE = mapIt(entry);
  52. for (char c : mapG.keySet()) {
  53. mismatch += Math.min(mapG.getOrDefault(c, 0), mapE.getOrDefault(c, 0));
  54. }
  55.  
  56. return exact * 10 + mismatch - exact;
  57. }
  58.  
  59. // Given string, count chars
  60. private static Map<Character, Integer> mapIt(String guess) {
  61. Map<Character, Integer> map = new HashMap<>();
  62. for (int i = 0; i < 5; i++) {
  63. map.put(guess.charAt(i), 1 + map.getOrDefault(guess.charAt(i), 0));
  64. }
  65. return map;
  66. }
  67.  
  68. public static void main(String[] args) {
  69. loadPossibilities();
  70. String answer = getRandomGuess();
  71.  
  72. while (options.size() > 1) {
  73. String guess = getRandomGuess();
  74. removeMatch(guess, computeMatch(guess, answer));
  75. System.out.println(guess + ":" + computeMatch(guess, answer) + ":" + options.size());
  76.  
  77. }
  78.  
  79. }
  80.  
  81. // Return one random string from the options
  82. private static String getRandomGuess() {
  83. List<String> asList = new ArrayList<>(options);
  84. Collections.shuffle(asList);
  85. return asList.get(0);
  86. }
  87.  
  88. }
  89.  
Time limit exceeded #stdin #stdout 5s 1064516KB
stdin
Standard input is empty
stdout
Standard output is empty