01647

ustreamer-01647

codeiq839スペーストーキー社の危機を救え!

http通信して答え合わせするコードを書かなかった点がダメ.書いたことなかったもんね.評価1.

後で書くか.

提出コード

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<?php

		function encode($input) {
			// 空文字列の場合と非[a-z]を含む場合
			$match = preg_match("/[^a-z]/", $input);
			if ($match === FALSE || $match === 1) {
				return "?";
			}
			// 文字列長制限
			if (strlen($input) > 1024) {
				return "?";
			}
			// TODO: エンコード
		}

		// 文字個数を調べるためのオフセット値
		define("ORDOFFSET", ord("a") - 1);

		/**
		 * "ac" -> "aaa". "ax" -> "aaaaaaaaaaaaaaaaaaaaaaaa"
		 *                         abcdefghijklmnopqrstuvwx
		 * @param type $input 2字
		 * @return string エンコードするとコマンドの2字になる文字列
		 */
		function decode($input) {
			$count = ord($input[1]) - ORDOFFSET;
			// 最初の文字を取り出し,count数だけ最初の文字で埋める
			return str_pad($input[0], $count, $input[0]);
		}

		/**
		 * 
		 * @param type $input コマンド
		 * @return string エンコードするとコマンドになる文字列
		 */
		function answer($input) {
			// 空文字列の場合と非[a-z]を含む場合
			$match = preg_match("/[^a-z]/", $input);
			if ($match === FALSE || $match === 1) {
				return "X";
			}
			// 文字列長が奇数である場合
			$length = strlen($input);
			if ($length % 2 === 1) {
				return "X";
			}
			$command = "";
			// 2字ずつ処理する
			for ($i = 0; $i < $length; $i += 2) {
				$command .= decode(substr($input, $i, 2));
			}
			// 文字列長制限
			if (strlen($command) > 1024) {
				return "X";
			}
			return $command;
		}

		// 改行コード単位で配列に読み込み
		$words = explode("\r\n", file_get_contents("words.txt"));
		// 作業する.元データを書き換えるから"&"付加
		foreach ($words as &$word) {
			if (strlen($word) > 0) {
				$word = answer($word) . ":" . $word;
			}
		}
		// 改行コードで連結しつつファイル出力
		file_put_contents("result.txt", implode("\r\n", $words));
		?>
	</body>
</html>