2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

「第3回オフラインリアルタイムどう書くの参考問題」をPHPで解く

Posted at

野球のスコアカウントを行います。
得点やランナー等の無い超簡易版です。

<?php

	class BASEBALL{
		
		/**
		* 野球のスコアカウント
		* @param  String 「ssbbbb」みたいな文字列
		* @return String 「010,020,021,022,023,000」みたいな文字列
		*/
		public function get($input){
			$baseball = [[0, 0, 0]];
			
			// すすめる
			for($i=0; $i<strlen($input); $i++){
				$baseball[] = $this->{'get'.strtoupper($input[$i])}(end($baseball));
			}
			
			// 文字列にして返す
			array_shift($baseball);
			$ret = '';
			foreach($baseball as $val){
				$ret .= ','.implode('',$val);
			}
			return substr($ret, 1);
		}
		
		// ストライク
		private function getS($input){
			// ストライク
			if(++$input[1] >= 3){
				$input[1] = 0;
				++$input[0];
				// アウト
				if($input[0] >=3){
					$input = [0, 0, 0];
				}
			}
			return $input;
		}
		
		// ボール
		private function getB($input){
			if(++$input[2] >= 4){
				$input[1] = $input[2] = 0;
			}
			return $input;
		}
		
		// ファウル
		private function getF($input){
			if($input[1] < 2){
				$input[1]++;
			}
			return $input;
		}
		
		// ヒット
		private function getH($input){
			$input[1] = $input[2] = 0;
			return $input;
		}
		
		// ピッチャーフライ
		private function getP($input){
			$input[1] = $input[2] = 0;
			// アウト
			if(++$input[0] >= 3){
				$input[0] = 0;
			}
			return $input;
		}
	}
	
	// テスト
	$test = [
		['s', '010'],
		['sss', '010,020,100'],
		['bbbb', '001,002,003,000'],
		['ssbbbb', '010,020,021,022,023,000'],
		['hsbhfhbh', '000,010,011,000,010,000,001,000'],
		['psbpfpbp', '100,110,111,200,210,000,001,100'],
		['ppp', '100,200,000'],
		['ffffs', '010,020,020,020,100'],
		['ssspfffs', '010,020,100,200,210,220,220,000'],
		['bbbsfbppp', '001,002,003,013,023,000,100,200,000'],
		['sssbbbbsbhsbppp', '010,020,100,101,102,103,100,110,111,100,110,111,200,000,100'],
		['ssffpffssp', '010,020,020,020,100,110,120,200,210,000']
	];

	$baseball = new BASEBALL();
	foreach($test as $key=>$data){
		$answer = $baseball->get($data[0]);
		if($answer !== $data[1]){
			print('えらー');
		}
	}

30分かからずで実装完了。
ひっかかるところが何一つ無かった。
やろうと思えば全サブルーチンを1行で実装可能ですが、そこまで削る必要もないでしょう。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?