忍者ブログ
[PR]
×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。



2024/04/20 12:55 |
PHP5.5.0 「第1回オフラインリアルタイムどう書くの問題」をPHPで解く
http://nabetani.sakura.ne.jp/hena/1/

三目並べの勝敗を決定します。
<?php
	class TICKTACKTOE{
		
		// 勝利パターン
		private $pattern = [
			'/o..o..o|^(...){0,2}ooo|o...o...o|..o.o.o../',
			'/x..x..x|^(...){0,2}xxx|x...x...x|..x.x.x../'
		];
		// プレイヤー
		private $player = ['o', 'x'];
		
		/**
		* 三目並べ
		* @param  String 「79538246」みたいな文字列
		* @return String 「x won.」みたいな文字列
		*/
		public function get($input){
			// 9文字で打ち切り
			$input = substr($input, 0, 9);
			// 初期化
			$tick = '---------';
			
			for($i=0; $i<strlen($input); $i++){
				// 既に入っていたら負け
				if($tick[$input[$i]-1] !== '-'){
					return 'Foul : '.$this->player[($i+1)%2].' won.';
				}
				
				// 該当値をセット
				$tick[$input[$i]-1] = $this->player[$i%2];
				
				// 勝っていれば終了
				if(preg_match($this->pattern[$i%2], $tick)){
					return $this->player[$i%2].' won.';
				}
			}
			
			// 引き分け
			return 'Draw game.';
		}
	}
	
	// テスト
	$test = [
		['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.'],
	];

	$ticktacktoe = new TICKTACKTOE();
	foreach($test as $key=>$data){
		$answer = $ticktacktoe->get($data[0]);
		if($answer !== $data[1]){
			print('えらー');
		}
	}
なんの変哲もなく、普通に正規表現で勝利パターンを引っかけてるだけです。
勝利パターンは8種類しかないので別に正規表現使わなくても十分だったりしますがまあいいや。

ちなみに「o..o..o」が縦、「^(...){0,2}ooo」が横、「o...o...o」「..o.o.o..」が斜めです。
まあ見ればわかるか。


「オフラインリアルタイムどう書く」の一覧

PR


2013/09/27 23:59 | Comments(0) | PHP

コメント

コメントを投稿する






Vodafone絵文字 i-mode絵文字 Ezweb絵文字 (絵文字)



<<今週の実績 2013/09/29 | HOME | PHP5.5.0 「第2回オフラインリアルタイムどう書くの参考問題」をPHPで解く>>
忍者ブログ[PR]