为了节省内存空间(提高运行效率)
把这部分代码:
// 珠玑妙算游戏类定义 public static class Mastermind { private int positions; // 位置数 private int colors; // 颜色数 private List<Integer> secret; // 秘密序列 private List<Integer> probabilitySpace; // 概率空间
中的:
private List<Integer> probabilitySpace; // 概率空间
修改成:
private char[] probabilitySpace; // 概率空间
不但节省了内存空间,还提高了运行效率:
// MasterMind.java : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class MasterMind {
// 处理输入,支持空格、逗号或无分隔符
public static void processInput(String input, List<Integer> result) {
input = input.replaceAll("[ ,]", ""); // 删除空格和逗号
// 检查输入是否只包含数字
if (!input.chars().allMatch(Character::isDigit)) {
System.err.println("输入无效。请输入仅包含数字的字符,中间可以用空格或逗号分隔。");
return;
}
// 将字符转换为数字并加入结果列表
for (char c : input.toCharArray()) {
result.add(c - '0');
}
}
// 珠玑妙算游戏类定义
public static class Mastermind {
private int positions; // 位置数
private int colors; // 颜色数
private List<Integer> secret; // 秘密序列
private char[] probabilitySpace; // 概率空间
public Mastermind(int numPositions, int numColors) {
positions = numPositions;
colors = numColors;
initializeProbabilitySpace();
}
// 生成秘密序列
public void generateSecret() {
secret = new ArrayList<>(positions);
Random rand = new Random();
for (int i = 0; i < positions; ++i) {
secret.add(rand.nextInt(colors));
System.out.print(secret.get(i) + " ");
}
System.out.println();
}
// 获取用户猜测
public void getUserGuess(List<Integer> guess) {
System.out.print("输入您的猜测 (例如:0012 表示一个4位的猜测): ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
// 验证输入的长度和字符合法性
if (input.length() != positions || !input.chars().allMatch(Character::isDigit)) {
System.err.println("输入无效。请确保输入正好有 " + positions + " 位数字 (0-9) 且不包含其他字符。");
getUserGuess(guess);
return;
}
guess.clear();
for (char c : input.toCharArray()) {
int digit = c - '0';
if (digit >= 0 && digit < colors) {
guess.add(digit);
} else {
System.err.println("输入无效。每位数字必须在 0 和 " + (colors - 1) + " 之间。");
getUserGuess(guess);
return;
}
}
}
// 提示结构体定义
public static class HintStruct {
int black; // 位置和颜色都正确的个数
int white; // 颜色正确但位置不对的个数
public HintStruct(int black, int white) {
this.black = black;
this.white = white;
}
}
// 评估用户猜测
public HintStruct evaluateGuess(List<Integer> guess) {
HintStruct hint = new HintStruct(0, 0);
boolean[] secretMatched = new boolean[positions];
boolean[] guessMatched = new boolean[positions];
// 检查位置和颜色都正确的情况
for (int i = 0; i < positions; ++i) {
if (guess.get(i).equals(secret.get(i))) {
hint.black++;
secretMatched[i] = true;
guessMatched[i] = true;
}
}
// 检查颜色正确但位置不对的情况
for (int i = 0; i < positions; ++i) {
if (!guessMatched[i]) {
for (int j = 0; j < positions; ++j) {
if (!secretMatched[j] && guess.get(i).equals(secret.get(j))) {
hint.white++;
secretMatched[j] = true;
break;
}
}
}
}
return hint;
}
// 评估概率
public HintStruct evaluateProbability(List<Integer> candidate, List<Integer> guess) {
HintStruct hint = new HintStruct(0, 0);
boolean[] candidateMatched = new boolean[positions];
boolean[] guessMatched = new boolean[positions];
// 检查位置和颜色都正确的情况
for (int i = 0; i < positions; ++i) {
if (candidate.get(i).equals(guess.get(i))) {
hint.black++;
candidateMatched[i] = true;
guessMatched[i] = true;
}
}
// 检查颜色正确但位置不对的情况
for (int i = 0; i < positions; ++i) {
if (!guessMatched[i]) {
for (int j = 0; j < positions; ++j) {
if (!candidateMatched[j] && guess.get(i).equals(candidate.get(j))) {
hint.white++;
candidateMatched[j] = true;
break;
}
}
}
}
return hint;
}
// 初始化概率空间
public void initializeProbabilitySpace() {
int size = (int) Math.pow(colors, positions);
probabilitySpace = new char[size];
for (int i = 0; i < size; ++i) {
probabilitySpace[i] = 1;
}
}
// 更新概率空间
public void updateProbabilitySpace(List<Integer> guess, HintStruct hint) {
int size = probabilitySpace.length;
for (int i = 0; i < size; ++i) {
if ( 1== probabilitySpace[i] ) {
List<Integer> candidate = decode(i);
HintStruct candidateHint = evaluateProbability(candidate, guess);
if (candidateHint.black != hint.black || candidateHint.white != hint.white) {
probabilitySpace[i] = 0;
}
if (i % 100000 == 0) {
System.out.print("" + i + "]");
}
}
}
}
// 返回剩余的可能性数量
public int remainingPossibilities() {
int count = 0;
for (char c : probabilitySpace) {
if (c == 1) {
count++;
}
}
return count;
}
// 检查是否解决
public boolean isSolved(HintStruct hint) {
return hint.black == positions;
}
// 解码索引为序列
public List<Integer> decode(int index) {
List<Integer> result = new ArrayList<>(positions);
for (int i = positions - 1; i >= 0; --i) {
result.add(index % colors);
index /= colors;
}
return result;
}
}
public static void main(String[] args) {
Random random = new Random();
random.setSeed(System.currentTimeMillis());
Scanner scanner = new Scanner(System.in);
System.out.print("欢迎来到珠玑妙算游戏…请输入位置数和颜色数,用空格分开(比如输入: 6 10【回车】表示,6位的10进制数字(或10种颜色做6位全排列): ");
int positions = scanner.nextInt();
int colors = scanner.nextInt();
Mastermind game = new Mastermind(positions, colors);
game.generateSecret();
List<Integer> guess = new ArrayList<>(positions);
while (true) {
System.out.println("\n剩余的可能性: " + game.remainingPossibilities());
game.getUserGuess(guess);
Mastermind.HintStruct hint = game.evaluateGuess(guess);
System.out.println("黑色 peg 数: " + hint.black + ", 白色 peg 数: " + hint.white);
if (game.isSolved(hint)) {
System.out.println("恭喜!您破解了密码!");
game.updateProbabilitySpace(guess, hint);
System.out.println("\n剩余的可能性: " + game.remainingPossibilities());
break;
}
game.updateProbabilitySpace(guess, hint);
}
}
}//main
// MasterMind.java : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class MasterMind {
// 处理输入,支持空格、逗号或无分隔符
public static void processInput(String input, List<Integer> result) {
input = input.replaceAll("[ ,]", ""); // 删除空格和逗号
// 检查输入是否只包含数字
if (!input.chars().allMatch(Character::isDigit)) {
System.err.println("输入无效。请输入仅包含数字的字符,中间可以用空格或逗号分隔。");
return;
}
// 将字符转换为数字并加入结果列表
for (char c : input.toCharArray()) {
result.add(c - '0');
}
}
// 珠玑妙算游戏类定义
public static class Mastermind {
private int positions; // 位置数
private int colors; // 颜色数
private List<Integer> secret; // 秘密序列
private List<Integer> probabilitySpace; // 概率空间
public Mastermind(int numPositions, int numColors) {
positions = numPositions;
colors = numColors;
initializeProbabilitySpace();
}
// 生成秘密序列
public void generateSecret() {
secret = new ArrayList<>(positions);
Random rand = new Random();
for (int i = 0; i < positions; ++i) {
secret.add(rand.nextInt(colors));
System.out.print(secret.get(i) + " ");
}
System.out.println();
}
// 获取用户猜测
public void getUserGuess(List<Integer> guess) {
System.out.print("输入您的猜测 (例如:0012 表示一个4位的猜测): ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
// 验证输入的长度和字符合法性
if (input.length() != positions || !input.chars().allMatch(Character::isDigit)) {
System.err.println("输入无效。请确保输入正好有 " + positions + " 位数字 (0-9) 且不包含其他字符。");
getUserGuess(guess);
return;
}
guess.clear();
for (char c : input.toCharArray()) {
int digit = c - '0';
if (digit >= 0 && digit < colors) {
guess.add(digit);
} else {
System.err.println("输入无效。每位数字必须在 0 和 " + (colors - 1) + " 之间。");
getUserGuess(guess);
return;
}
}
}
// 提示结构体定义
public static class HintStruct {
int black; // 位置和颜色都正确的个数
int white; // 颜色正确但位置不对的个数
public HintStruct(int black, int white) {
this.black = black;
this.white = white;
}
}
// 评估用户猜测
public HintStruct evaluateGuess(List<Integer> guess) {
HintStruct hint = new HintStruct(0, 0);
boolean[] secretMatched = new boolean[positions];
boolean[] guessMatched = new boolean[positions];
// 检查位置和颜色都正确的情况
for (int i = 0; i < positions; ++i) {
if (guess.get(i).equals(secret.get(i))) {
hint.black++;
secretMatched[i] = true;
guessMatched[i] = true;
}
}
// 检查颜色正确但位置不对的情况
for (int i = 0; i < positions; ++i) {
if (!guessMatched[i]) {
for (int j = 0; j < positions; ++j) {
if (!secretMatched[j] && guess.get(i).equals(secret.get(j))) {
hint.white++;
secretMatched[j] = true;
break;
}
}
}
}
return hint;
}
// 评估概率
public HintStruct evaluateProbability(List<Integer> candidate, List<Integer> guess) {
HintStruct hint = new HintStruct(0, 0);
boolean[] candidateMatched = new boolean[positions];
boolean[] guessMatched = new boolean[positions];
// 检查位置和颜色都正确的情况
for (int i = 0; i < positions; ++i) {
if (candidate.get(i).equals(guess.get(i))) {
hint.black++;
candidateMatched[i] = true;
guessMatched[i] = true;
}
}
// 检查颜色正确但位置不对的情况
for (int i = 0; i < positions; ++i) {
if (!guessMatched[i]) {
for (int j = 0; j < positions; ++j) {
if (!candidateMatched[j] && guess.get(i).equals(candidate.get(j))) {
hint.white++;
candidateMatched[j] = true;
break;
}
}
}
}
return hint;
}
// 初始化概率空间
public void initializeProbabilitySpace() {
int size = (int) Math.pow(colors, positions);
probabilitySpace = new ArrayList<>(size);
for (int i = 0; i < size; ++i) {
probabilitySpace.add(1);
}
}
// 更新概率空间
public void updateProbabilitySpace(List<Integer> guess, HintStruct hint) {
int size = probabilitySpace.size();
for (int i = 0; i < size; ++i) {
if (probabilitySpace.get(i) == 1) {
List<Integer> candidate = decode(i);
HintStruct candidateHint = evaluateProbability(candidate, guess);
if (candidateHint.black != hint.black || candidateHint.white != hint.white) {
probabilitySpace.set(i, 0);
}
if (i % 100000 == 0) {
System.out.print("" + i + "]");
}
}
}
}
// 返回剩余的可能性数量
public int remainingPossibilities() {
return (int) probabilitySpace.stream().filter(p -> p == 1).count();
}
// 检查是否解决
public boolean isSolved(HintStruct hint) {
return hint.black == positions;
}
// 解码索引为序列
public List<Integer> decode(int index) {
List<Integer> result = new ArrayList<>(positions);
for (int i = positions - 1; i >= 0; --i) {
result.add(index % colors);
index /= colors;
}
return result;
}
}
public static void main(String[] args) {
Random random = new Random();
random.setSeed(System.currentTimeMillis());
Scanner scanner = new Scanner(System.in);
System.out.print("欢迎来到珠玑妙算游戏…请输入位置数和颜色数,用空格分开(比如输入: 6 10【回车】表示,6位的10进制数字(或10种颜色做6位全排列): ");
int positions = scanner.nextInt();
int colors = scanner.nextInt();
Mastermind game = new Mastermind(positions, colors);
game.generateSecret();
List<Integer> guess = new ArrayList<>(positions);
while (true) {
System.out.println("\n剩余的可能性: " + game.remainingPossibilities());
game.getUserGuess(guess);
Mastermind.HintStruct hint = game.evaluateGuess(guess);
System.out.println("黑色 peg 数: " + hint.black + ", 白色 peg 数: " + hint.white);
if (game.isSolved(hint)) {
System.out.println("恭喜!您破解了密码!");
game.updateProbabilitySpace(guess, hint);
System.out.println("\n剩余的可能性: " + game.remainingPossibilities());
break;
}
game.updateProbabilitySpace(guess, hint);
}
}//main
}//public class MasterMind