第1回オフラインリアルタイムどう書くJavaでの解答
Tick-Tack-Toeの解答
実行方法: java tictactoe/Main < input.txt
Main.java
package tictactoe;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
//反則だったり、どちらかが勝ったらtrueを返す。
private static String finished(int[] stage, int i, int pos) {
if(!isRegal(stage, pos)) {
return String.format("Foul : %s won.", (i % 2 == 1)?"o": "x");
} else {
stage[pos] = (i % 2 == 0)? 1 : 2;
if(isFill(stage, pos)) {
return String.format("%s won.", (i % 2 == 0)? "o" : "x");
}
}
return null;
}
private static boolean isFill(int[] stage, int pos) {
int v = stage[pos];
int x = pos % 3;
int y = pos / 3;
boolean a = (stage[position((x + 1) % 3, y)] == v && stage[position((x + 2) % 3, y)] == v) ||
(stage[position(x, (y + 1) % 3)] == v && stage[position(x, (y + 2) % 3)] == v);
boolean b = (stage[0] == stage[4] && stage[4] == stage[8] && stage[4] != 0) ||
(stage[2] == stage[4] && stage[4] == stage[6] && stage[4] != 0);
return a || b;
}
private static int position(int x, int y) {
return x + y * 3;
}
private static boolean isRegal(int[] stage, int pos) {
return stage[pos] == 0;
}
private static String game(String inp) {
// ○: 1, ×: 2
int[] stage = new int[9];
char[] chs = inp.toCharArray();
String msg = null;
for(int i = 0; i < 9; i++) {
if((msg = finished(stage, i, (int)(chs[i] - '0')-1)) != null) return msg;
}
return "Draw game.";
}
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String line = null;
while ((line = br.readLine()) != null) {
String[] a = line.split("\\t");
if(game(a[1]).equals(a[2])) {
System.out.println(a[0] + ":" + game(a[1]));
} else {
System.out.println(a[0] + ":" + a[1]);
System.out.println("actual :\"" + game(a[1]) +"\"");
System.out.println("expected:\"" + a[2] +"\"");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
input.txt
1 79538246 x won.
2 35497162193 x won.
3 61978543 x won.
4 254961323121 x won.
5 6134278187 x won.
6 4319581 Foul : x won.
7 9625663381 Foul : x won.
8 7975662 Foul : x won.
9 2368799597 Foul : x won.
10 18652368566 Foul : x won.
11 965715 o won.
12 38745796 o won.
13 371929 o won.
14 758698769 o won.
15 42683953 o won.
16 618843927 Foul : o won.
17 36535224 Foul : o won.
18 882973 Foul : o won.
19 653675681 Foul : o won.
20 9729934662 Foul : o won.
21 972651483927 Draw game.
22 5439126787 Draw game.
23 142583697 Draw game.
24 42198637563 Draw game.
25 657391482 Draw game.
Author And Source
この問題について(第1回オフラインリアルタイムどう書くJavaでの解答), 我々は、より多くの情報をここで見つけました https://qiita.com/nnabeyang/items/9cbb05b41550e443362d著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .