- https://www.codewars.com/kata/5870fa11aa0428da750000da RoboScript #2 - Implement the RS1 Specification.
Started at 23:47 30.10.2020 Friday Oct.
Finished at 3:12 31.10.2020 Satruday Oct. (3hrs 58minutes)
<?php | |
# https://www.codewars.com/kata/5870fa11aa0428da750000da RoboScript #2 - Implement the RS1 Specification. | |
function execute(string $code): string { | |
$dir = 0; | |
$delta = [[1,0],[0,-1],[-1,0],[0,+1]]; | |
$x = 0; $y = 0; | |
$h = ['0;0' => true]; | |
$xmin = 0; $xmax = 0; | |
$ymin = 0; $ymax = 0; | |
$commands = get_commands($code); | |
foreach($commands as $v){ | |
$number = $v[1]; | |
$command = $v[0]; | |
for($i = 0; $i < $number; $i += 1){ | |
if("F" == $command){ | |
$x += $delta[$dir][0]; | |
$y += $delta[$dir][1]; | |
$coord = "$x;$y"; | |
$h[$coord] = true; | |
$xmax = max($x,$xmax); $xmin = min($x,$xmin); | |
$ymax = max($y,$ymax); $ymin = min($y,$ymin); | |
} | |
if( "L" == $command){ $dir = ($dir+3)%4; } | |
if( "R" == $command){ $dir = ($dir+1)%4; } | |
} | |
} | |
$width = $xmax - $xmin + 1; | |
$height = $ymax - $ymin + 1; | |
$a = array_fill(0,$height,0); | |
for($i = 0; $i < $height; $i+=1) $a[$i] = array_fill(0,$width," "); | |
for($i = 0; $i < $height; $i += 1) | |
for($j = 0; $j < $width; $j += 1){ | |
$xcoord = $xmin+$j; | |
$ycoord = $ymax - $i; | |
$str = "$xcoord;$ycoord"; | |
if(isset($h[$str])) $a[$i][$j] = "*"; | |
} | |
for($i = 0; $i < $height; $i += 1) $a[$i] = implode($a[$i]); | |
return implode($a,"\r\n"); | |
} | |
function get_commands($str){ | |
$match = []; | |
if(preg_match_all('/[A-Z]\d*/',$str,$match)) return array_map("split_num",$match[0]); | |
return []; | |
} | |
function split_num($str){ | |
if(preg_match('/^[A-Z]$/', $str)) return [$str,1]; | |
return [substr($str,0,1),intval(substr($str,1))]; | |
} |
Started at 23:47 30.10.2020 Friday Oct.
Finished at 3:12 31.10.2020 Satruday Oct. (3hrs 58minutes)