1
1

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.

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

Posted at

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分足らず。

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

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?