3
3

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.

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

Posted at

画像を回転させる問題です。
絶対に誰も真似しない方法で回答。

<?php

	class ROTATE{
		
		/**
		* 画像を回転させる
		* @param  String 「3:5b8」みたいな文字列
		* @return String 「3:de0」みたいな文字列
		*/
		public function get($input){
			// 入力を2進数に
			list($size, $hex) = explode(':', $input);
			$bit = '';
			$tmp = str_split($hex, 4);
			foreach($tmp as $key=>$val){
				$bit .= sprintf('%0'.(strlen($val)*4).'s', base_convert($val, 16, 2));
			}
			
			// 指定サイズの黒画像を作成
			$image = imagecreatetruecolor($size, $size);
			$dot = imagecolorallocate($image, 0, 0, 1);
			
			// 1のビットに点を打つ
			for($y=0; $y<$size; $y++){
				for($x=0; $x<$size; $x++){
					if($bit[$x+$y*$size]){
						imagesetpixel($image, $x, $y, $dot);
					}
				}
			}
			
			// 画像を回転
			$image = imagerotate($image, 270, 0);
			
			// 色を取得
			$rot = '';
			for($y=0; $y<$size; $y++){
				for($x=0; $x<$size; $x++){
					$rot .= imagecolorat($image, $x, $y);
				}
			}
			imagedestroy($image);
			
			// 16進数にして戻す
			$rot = str_pad($rot, (strlen($bit)), '0', STR_PAD_RIGHT);
			$ret = '';
			$tmp = str_split($rot, 16);
			foreach($tmp as $key=>$val){
				$ret .= sprintf('%0'.(strlen($val)/4).'s', base_convert($val, 2, 16));
			}
			return $size . ':' . $ret;
		}
	}
	
	// テスト
	$test = [
		['3:5b8', '3:de0'],
		['1:8', '1:8'],
		['2:8', '2:4'],
		['2:4', '2:1'],
		['2:1', '2:2'],
		['3:5d0', '3:5d0'],
		['4:1234', '4:0865'],
		['5:22a2a20', '5:22a2a20'],
		['5:1234567', '5:25b0540'],
		['6:123456789', '6:09cc196a6'],
		['7:123456789abcd', '7:f1a206734b258'],
		['7:fffffffffffff', '7:ffffffffffff8'],
		['7:fdfbf7efdfbf0', '7:ffffffffffc00'],
		['8:123456789abcdef1', '8:f0ccaaff78665580'],
		['9:112233445566778899aab', '9:b23da9011d22daf005d40'],
	];

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

実際に画像を作って回転させました。
もちろん、このような回りくどいことをする必要性は皆無です。
単にやってみたかっただけという。

なおbase_convert()のあたりがややこしいのは、16桁以上の16進数をbase_convert()に突っ込むと正しくない値が返ってきてしまうせいです。
そのせいで最後の2サンプルだけ正しく動かなかったという。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?