京东笔试:三子棋
2016-04-09 10:57
387 查看
考试当时未通过,这是我后来写的代码,有错误请指出
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static final char X = 'X'; public static final char O = 'O'; public static int check(char[][] a) { int xflag = 0; int oflag = 0; // - for (int i = 0; i < 3; i++) { if (a[i][0] != '.' && a[i][0] == a[i][1] && a[i][0] == a[i][2]) { if (a[i][0] == X) xflag = 1; else oflag = 1; } } // | for (int i = 0; i < 3; i++) { if (a[0][i] != '.' && a[0][i] == a[1][i] && a[0][i] == a[2][i]) { if (a[0][i] == X) xflag = 1; else oflag = 1; } } // \ if (a[0][0] != '.' && a[0][0] == a[1][1] && a[0][0] == a[2][2]) { if (a[0][0] == X) xflag = 1; else oflag = 1; } // / if (a[0][2] != '.' && a[0][2] == a[1][1] && a[0][0] == a[2][0]) { if (a[0][2] == X) xflag = 1; else oflag = 1; } if (xflag == 1 && oflag == 0) { return 1; } else if (xflag == 0 && oflag == 1) { return 2; } else if (xflag == 1 && oflag == 1){ return 3; } else { return 0; } } public static Map<String, Object> count(char a[][]) { Map<String, Object> res = new HashMap<String, Object>(); Integer x = 0; Integer o = 0; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { if (a[i][j] == X) { x++; } else if (a[i][j] == O) { o++; } } } res.put("x", x); res.put("o", o); return res; } public static void main(String[] args) { Scanner cin = new Scanner(System.in); while (cin.hasNext()) { char a[][] = new char[3][3]; for (int i = 0; i < 3; i++) { String s = cin.next(); a[i][0] = s.charAt(0); a[i][1] = s.charAt(1); a[i][2] = s.charAt(2); } Map<String, Object> res = count(a); Integer x = (Integer) res.get("x"); Integer o = (Integer) res.get("o"); Integer winner = check(a); if (winner == 1) { // 先手获胜或者不合法 if (x - o == 1 && x + o <= 9) { System.out.println("1 won"); } else { System.out.println("x"); } } else if (winner == 2) { // 后手获胜或者不合法 if (x - o == 0 && x + o <= 9) { System.out.println("2 won"); } else { System.out.println("x"); } } else if(winner==3) { System.out.println("x"); } else { // 无获胜 if (x + o == 9 && x == 5 && o == 4) {// 平局 System.out.println("Draw"); } else if (x + o < 9 && x - o == 1) {// 先手 System.out.println(1); } else if (x + o < 9 && x == o) {// 后手 System.out.println(2); } else { System.out.println("x"); } } } } }
相关文章推荐
- Machine Learning 线性回归( Linear Regression) Andrew Ng 课程练习 Matlab Script 详细解析
- SQLite 粗劣内容
- Android 并发网络请求的处理
- qt中moc的作用
- 动态添加学生成员,重载运算符的练习。
- Ubuntu14.04+Caffe+CPU,挖挖坑坑
- 抽象方法与接口
- 相邻整数
- 结对编程之队友篇
- 开发中js常用的格式化方法
- C#使用MySQLConnectorNet和MySQLDriverCS操作MySQL的方法
- python 分页
- OpenJudge 1806:词典find()与end()
- 利用Sharepoint 创建轻量型应用之基本功能配置!
- IOCCC 1987 最佳单行代码解读
- 蓝桥杯-基础练习-十六进制转十进制
- 如何将ArrayList转换成整型数组
- Codeforces Round #305 (Div. 2) A
- postMan 使用
- Python之路【第十八篇】Django小项目webQQ实现