Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Last active October 30, 2020 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbvf50mobile/8d20c14ab42d7db5ef88e3b7a92a4e5a to your computer and use it in GitHub Desktop.
Save lbvf50mobile/8d20c14ab42d7db5ef88e3b7a92a4e5a to your computer and use it in GitHub Desktop.
Just PHP FUN 141.
<?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))];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment