忍者ブログ
[PR]
×

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



2024/04/26 14:46 |
PHP5.5.0 「第6回オフラインリアルタイムどう書くの問題」をPHPで解く
http://qiita.com/Nabetani/items/5e1c944541f09f0f9711
http://nabetani.sakura.ne.jp/hena/ord6kinship/

家系図から二人の関係を算出します。

<?php
	class RELATIONSHIP{
		
		/**
		* 続柄を返す
		* @param  String 「5->2」みたいな文字列
		* @return String 「mo」みたいな文字列
		*/
		public function get($input){
			// 続柄
			$relation = ['me', 'mo', 'da', 'si', 'au', 'ni', 'co'];
		
			// ->で分割
			list($from, $to) = explode('->', $input, 2);
			$from = (int)$from;
			$to = (int)$to;
			
			// 続柄判断
			foreach($relation as $val){
				if($this->{'is'.ucfirst($val)}($from, $to)){ return $val; }
			}
			return '-';
		}
		
		// 自分自身であるか
		private function isMe($from, $to){
			return $from === $to;
		}
		
		// 親であるか
		private function isMo($from, $to){
			return $this->getMo($from) === $to;
		}
		
		// 娘であるか
		private function isDa($from, $to){
			return $this->getMo($to) === $from;
		}
		
		// 姉妹であるか
		private function isSi($from, $to){
			return $this->getMo($from) === $this->getMo($to);
		}
		
		// おばであるか
		private function isAu($from, $to){
			return $this->getMo($this->getMo($from)) === $this->getMo($to);
		}
		
		// 姪であるか
		private function isNi($from, $to){
			return $this->getMo($this->getMo($to)) === $this->getMo($from);
		}
		
		// いとこであるか
		private function isCo($from, $to){
			return $this->getMo($this->getMo($to)) === $this->getMo($this->getMo($from));
		}
		
		// 母を取得
		private function getMo($from){
			return intval(($from+1)/3);
		}
	}
	
	// テスト
	$test = [
		['5->2', 'mo'],
		/* 省略 */
	];

	$relationship = new RELATIONSHIP();
	foreach($test as $key=>$data){
		$answer = $relationship->get($data[0]);
		if($answer !== $data[1]){
			print('えらー');
		}
	}
とりあえず各メソッドを作っていたら答えになっていた。
時間は30分足らず。

さてロジックをよく見てみると、姉妹であるかのチェックで、自分自身ではないという確認を行っていません。
よって実際は正確な判定ではないのですが、しかし今回は先に自分自身であるかを確認しているので事実上問題ありません。
おば判定で親チェックを行っていない、いとこ判定で姉妹や自分自身チェックを行っていないことについても同様です。
順不同でもきちんと判定を行いたいのであればそこらのチェックも必要になります。


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

PR


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

コメント

コメントを投稿する






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



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