第一回 オフラインリアルタイムどう書く の回答


http://nabetani.sakura.ne.jp/hena/1/ の回答

実行方法

$php main.php < input.txt

スクリプトとインプットファイル

main.php
<?php
function ox($i) {
  return ($i == 0)? "o" : "x";
}
function play_game($str) {
  $board = array_fill(0, 9, 0);
  for($i = 0; $i < 9; $i++) {
    $p = $i % 2;
    $v = intval($str[$i]) - 1;
    if($board[$v] != 0) return sprintf("Foul : %s won.", ox(($i + 1) % 2));
    else                $board[$v] = $p + 1;
    if(($board[0] & $board[1] & $board[2]) ||
       ($board[3] & $board[4] & $board[5]) ||
       ($board[6] & $board[7] & $board[8]) ||
       ($board[0] & $board[3] & $board[6]) ||
       ($board[1] & $board[4] & $board[7]) ||
       ($board[2] & $board[5] & $board[8]) ||
       ($board[0] & $board[4] & $board[8]) ||
       ($board[2] & $board[4] & $board[6]))
       return sprintf("%s won.", ox($p));
  }
    return "Draw game.";
}
while(preg_match('/(\d+)\s*(.*)/',fgets(STDIN), $m)) {
    $res = play_game(strval($m[1]));
    if($res != chop($m[2])) {
      printf("input:%s\n", $m[1]); 
      printf("result = %s\n", $res);
      printf("actual = %s\n", chop($m[2]));
    }
}

インプットファイル。
text:input.txt
79538246 x won.
35497162193 x won.
61978543 x won.
254961323121 x won.
6134278187 x won.
4319581 Foul : x won.
9625663381 Foul : x won.
7975662 Foul : x won.
2368799597 Foul : x won.
18652368566 Foul : x won.
965715 o won.
38745796 o won.
371929 o won.
758698769 o won.
42683953 o won.
618843927 Foul : o won.
36535224 Foul : o won.
882973 Foul : o won.
653675681 Foul : o won.
9729934662 Foul : o won.
972651483927 Draw game.
5439126787 Draw game.
142583697 Draw game.
42198637563 Draw game.
657391482 Draw game.