import java.io.*;
public class GuessNumber {
private int[] answerSet = new int[10*9*8*7];
public GuessNumber() {
int index=0;
for (int n1=0; n1<10; n1++) {
for (int n2=0; n2<10; n2++) {
if ( n2 == n1) continue;
for (int n3=0; n3<10; n3++) {
if (n3 == n2 || n3 == n1 ) continue;
for (int n4=0; n4<10; n4++) {
if ( n4==n1 || n4==n2 || n4==n3) continue;
answerSet[index++] = n1*1000+n2*100+n3*10+n4;
}
}
}
}
guess();
}
private void input(int number) {
System.out.print( transform(number) + ", ?A?B = ");
int a=0,b=0;
try {
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
String str = br.readLine();
while ( str.length() != 4 ) {
System.out.println("輸入錯誤, 格式為 ?A?B ");
System.out.print( transform(number) + ", ?A?B = ");
str = br.readLine();
}
a = str.charAt(0) - '0';
b = str.charAt(2) - '0';
}
catch (IOException e) {
System.out.println("輸入時發生不可預期的錯誤...");
System.exit(0);
}
if (a == 4) {
System.out.println("The answer is " + transform(number));
System.exit(0);
}
reduce(number,a,b);
}
private void guess() {
for (int i=0; i< answerSet.length; i++) {
if ( answerSet[i] == -1 ) continue;
input ( answerSet[i]);
}
System.out.println("你騙人!! 根本沒這數字, ***!");
}
private void reduce(int number, int a, int b) {
for (int i=0; i< answerSet.length; i++) {
if ( answerSet[i] == -1) continue;
if (getA(number,answerSet[i]) != a || getB(number,answerSet[i]) != b )
answerSet[i] = -1;
}
for (int i=0; i < answerSet.length; i++) {
if ( answerSet[i] == -1) continue;
System.out.print( transform(answerSet[i]) + " ");
}
System.out.println();
}
private int getA(int n1, int n2) {
int a=0;
String str1 = transform(n1);
String str2 = transform(n2);
for (int i=0; i<4; i++) {
if (str1.charAt(i) == str2.charAt(i) )
a++;
}
return a;
} private String transform (int n) {
if ( n < 1000 )
return "0" + n;
else
return ""+n;
}
private int getB(int n1, int n2) {
int b = 0;
String str1 = transform(n1);
String str2 = transform(n2);
for (int i=0; i < 4; i++) {
for (int j=0; j<4 ; j++) {
if ( i == j) continue;
if ( str1.charAt(i) == str2.charAt(j) )
b++;
}
}
return b;
}
public static void main (String [] args) {
GuessNumber app = new GuessNumber();
}
}
參考來源
網頁
BloggerAds 廣告
標籤
- Java (96)
- Android (27)
- 演算法 (21)
- c++ (19)
- JavaScript (7)
- OpenMp (6)
- Design Pattern (4)
- 日文歌曲 (4)
- 資料結構 (4)
- Foundation Knowledge Of Programming (3)
- QUT (2)
- CodingHomeWork (1)
- Database (1)
- 英文歌詞 (1)
搜尋此網誌
2013年6月14日 星期五
猜數字遊戲
訂閱:
張貼留言 (Atom)
我的網誌清單
標籤
日文歌曲
(4)
股市
(7)
股票
(9)
英文歌詞
(1)
時事
(1)
硬體(hardware)
(1)
資料結構
(4)
演算法
(21)
數學(Math)
(4)
ACM
(3)
ajax
(7)
algorithms
(1)
Android
(27)
Blog Notes(部落格記事)
(6)
C
(9)
c++
(19)
CodingHomeWork
(1)
Database
(1)
Design Pattern
(4)
Foundation Knowledge Of Programming
(3)
GWT
(1)
How
(2)
J2EE
(1)
Java
(96)
Java語言
(4)
JavaScript
(7)
Leetcode
(4)
LOL
(1)
OpenMp
(6)
QUT
(2)
Uva
(2)
Yahoo知識問答
(11)
沒有留言:
張貼留言