Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Last active October 31, 2020 18:24
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/2b030904c55db59c76424b8eddc2208f to your computer and use it in GitHub Desktop.
Save lbvf50mobile/2b030904c55db59c76424b8eddc2208f to your computer and use it in GitHub Desktop.
Just PHP FUN 142.
<?php
# https://www.codewars.com/kata/58738d518ec3b4bf95000192 RoboScript #3 - Implement the RS2 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;
$code = unfolder($code);
$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))];
}
function unfolder($str){
echo "unfolder: $str \n";
$str .= " ";
$ans = "";
$tmp = "";
$cnt = 0;
for($i = 0; $i < strlen($str); $i+=1){
$e = $str[$i];
if(0 == $cnt){
if('(' != $e){ $ans .= $e; }
else{ $cnt += 1; $tmp = ""; }
}else{
if(')' == $e && $cnt == 1){
$cnt -= 1;
$number = "";
for( $j = $i + 1 ; $j < strlen($str) && preg_match('/[0-9]/',$str[$j]); $j += 1) $number .= $str[$j];
$i = $j - 1;
$x = intval($number);
$number = $x > 0 ? $x : 1;
$tmp = unfolder($tmp);
$tmp = str_repeat($tmp,$number);
$ans .= $tmp;
}else{
$tmp .= $e;
if("(" == $e) $cnt += 1;
if(")" == $e) $cnt -= 1;
}
}
}
return trim($ans);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment