第一回 オフラインリアルタイムどう書くの問題をDartで解いてみました。
[http://nabetani.sakura.ne.jp/hena/1/]
結構手こずって、2時間以上かかりました。
import "dart:io";
import "dart:math";
final List<int> clearFlags = [7, 56, 448, 73, 146, 292, 273, 84];
int nthBit(n) => 1 << (n - 1);
bool isClear(int state) => clearFlags.any((int flag) => (flag & state) == flag);
String solve_tic_tack_toe(String input) {
int playerO = 0;
int playerX = 0;
int common = 0;
for(var i = 0; i < 9; i++) {
int bit = nthBit(int.parse(input[i]));
if(i % 2 == 0) {
if((bit & common) != 0) return "Foul : x won.";
playerO |= bit;
if(isClear(playerO)) return "o won.";
} else {
if((bit & common) != 0) return "Foul : o won.";
playerX |= bit;
if(isClear(playerX)) return "x won.";
}
common |= bit;
}
return "Draw game.";
}
test(input, expect) {
assert(solve_tic_tack_toe(input) == expect);
}
main() {
test("79538246" , "x won.");
test("35497162193" , "x won.");
test("61978543" , "x won.");
test("254961323121", "x won.");
test("6134278187" , "x won.");
test("4319581" , "Foul : x won.");
test("9625663381" , "Foul : x won.");
test("7975662" , "Foul : x won.");
test("2368799597" , "Foul : x won.");
test("18652368566" , "Foul : x won.");
test("965715" , "o won.");
test("38745796" , "o won.");
test("371929" , "o won.");
test("758698769" , "o won.");
test("42683953" , "o won.");
test("618843927" , "Foul : o won.");
test("36535224" , "Foul : o won.");
test("882973" , "Foul : o won.");
test("653675681" , "Foul : o won.");
test("9729934662" , "Foul : o won.");
test("972651483927", "Draw game.");
test("5439126787" , "Draw game.");
test("142583697" , "Draw game.");
test("42198637563" , "Draw game.");
test("657391482" , "Draw game.");
print("ok");
}