You are on page 1of 5

import java.util.

HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;

public class BandC {


public static void main(String[] args) {
Set<String> possibleNums = generatePossibleNums();
int steps = 0;
int maxSteps = 6;
System.out.println("Hello! I am your computer!\nNow think of a number...");
Scanner reader = new Scanner(System.in);
while (true) {
steps++;
if (steps > maxSteps) {
System.out.println("Exceeded maximum number of steps. The correct
number wasn't guessed.");
break;
}
Iterator<String> iter = possibleNums.iterator();
String AIguess = iter.next();
System.out.println("My guess is: " + AIguess);
System.out.print("Number of cows:");
int numberOfCows = reader.nextInt();
System.out.print("Number of bulls:");
int numberOfBulls = reader.nextInt();
removeWrongNums(new BcCount(numberOfBulls, numberOfCows), AIguess,
possibleNums);
if (numberOfBulls == 4) {
System.out.println("Guessed in " + steps + " steps");
break;
}
}
reader.close();
}

// Hàm tính số lượng bulls và cows


public static BcCount calcBullandCowCount(String guess, String candidate) {
BcCount bcCount = new BcCount(0, 0);
for (int i = 0; i < candidate.length(); i++) {
if (guess.charAt(i) == candidate.charAt(i)) {
bcCount.bullCount++;
} else if (guess.contains(String.valueOf(candidate.charAt(i)))) {
bcCount.cowCount++;
}
}
return bcCount;
}

// Tạo danh sách các số có thể từ 1000 đến 9999 thỏa mãn điều kiện
public static Set<String> generatePossibleNums() {
Set<String> set = new HashSet<String>();
for (int i = 1000; i < 10000; i++) {
String num = String.valueOf(i);
if (!num.contains("0") && !num.contains("7") && !num.contains("8") && !
num.contains("9")) {
Set<Character> digits = new HashSet<>();
boolean hasDuplicate = false;
for (char c : num.toCharArray()) {
if (!digits.add(c)) {
hasDuplicate = true;
break;
}
}
if (!hasDuplicate) {
set.add(num);
}
}
}
return set;
}

// Loại bỏ các số không đúng từ danh sách các số có thể


public static void removeWrongNums(BcCount guessBcCount, String guess,
Set<String> possibleNums) {
Iterator<String> iter = possibleNums.iterator();
while (iter.hasNext()) {
String str = iter.next();
if (calcBullandCowCount(guess, str).equals(guessBcCount) == false) {
iter.remove();
}
}
}
}

// Class BcCount để lưu trữ số lượng bulls và cows


class BcCount {
public int bullCount = 0;
public int cowCount = 0;

public BcCount(int b, int c) {


bullCount = b;
cowCount = c;
}

// Phương thức toString để hiển thị số bulls và cows


public String toString() {
return bullCount + " " + cowCount;
}

// Phương thức equals để so sánh số bulls và cows giữa hai đối tượng BcCount
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BcCount other = (BcCount) obj;
if (bullCount != other.bullCount)
return false;
if (cowCount != other.cowCount)
return false;
return true;
}
}

You might also like