# RoboScript #2 - Implement the RS1 Specification

## Disclaimer

The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental.

## About this Kata Series

This Kata Series is based on a fictional story about a computer scientist and engineer who owns a firm that sells a toy robot called MyRobot which can interpret its own (esoteric) programming language called RoboScript.  Naturally, this Kata Series deals with the software side of things (I'm afraid Codewars cannot test your ability to build a physical robot!).

## Story

Now that you've built your own code editor for RoboScript with appropriate syntax highlighting to make it look like serious code, it's time to properly implement RoboScript so that our MyRobots can execute any RoboScript provided and move according to the will of our customers.  Since this is the first version of RoboScript, let's call our specification RS1 (like how the newest specification for JavaScript is called ES6 :p)

## Task

Write an interpreter for RS1 called `execute()` which accepts 1 required argument `code`, the RS1 program to be executed.  The interpreter should return a string representation of the smallest 2D grid containing the full path that the MyRobot has walked on (explained in more detail later).

Initially, the robot starts at the middle of a 1x1 grid.  Everywhere the robot walks it will leave a path `"*"`.  If the robot has not been at a particular point on the grid then that point will be represented by a whitespace character `" "`.  So if the RS1 program passed in to `execute()` is empty, then:

```
""  -->  "*"
```

The robot understands 3 major commands:

- `F` - Move forward by 1 step in the direction that it is currently pointing.  Initially, the robot faces to the right.
- `L` - Turn "left" (i.e. **rotate** 90 degrees **anticlockwise**)
- `R` - Turn "right" (i.e. **rotate** 90 degrees **clockwise**)

As the robot moves forward, if there is not enough space in the grid, the grid should expand accordingly. So:

```
"FFFFF"  -->  "******"
```

As you will notice, 5 `F` commands in a row should cause your interpreter to return a string containing 6 `"*"`s in a row.  This is because initially, your robot is standing at the middle of the 1x1 grid facing right.  It leaves a mark on the spot it is standing on, hence the first `"*"`.  Upon the first command, the robot moves 1 unit to the right.  Since the 1x1 grid is not large enough, your interpreter should expand the grid 1 unit to the right.  The robot then leaves a mark on its newly arrived destination hence the second `"*"`.  As this process is repeated 4 more times, the grid expands 4 more units to the right and the robot keeps leaving a mark on its newly arrived destination so by the time the entire program is executed, 6 "squares" have been marked `"*"` from left to right.

Each row in your grid must be separated from the next by a CRLF (`\r\n`).  Let's look at another example:

```
"FFFFFLFFFFFLFFFFFLFFFFFL"  -->  "******\r\n*    *\r\n*    *\r\n*    *\r\n*    *\r\n******"
```

So the grid will look like this:
```
******
*    *
*    *
*    *
*    *
******
```

The robot moves 5 units to the right, then turns left, then moves 5 units upwards, then turns left again, then moves 5 units to the left, then turns left again and moves 5 units downwards, returning to the starting point before turning left one final time.  Note that the marks do **not** disappear no matter how many times the robot steps on them, e.g. the starting point is still marked `"*"` despite the robot having stepped on it twice (initially and on the last step).

Another example:

```
"LFFFFFRFFFRFFFRFFFFFFF"  -->  "    ****\r\n    *  *\r\n    *  *\r\n********\r\n    *   \r\n    *   "
```
So the grid will look like this:
```
    ****
    *  *
    *  *
********
    *
    *
```

Initially the robot turns left to face upwards, then moves upwards 5 squares, then turns right and moves 3 squares, then turns right again (to face downwards) and move 3 squares, then finally turns right again and moves 7 squares.

Since you've realised that it is probably quite inefficient to repeat certain commands over and over again by repeating the characters (especially the `F` command - what if you want to move forwards 20 steps?), you decide to allow a shorthand notation in the RS1 specification which allows your customers to postfix a non-negative integer onto a command to specify how many times an instruction is to be executed:

- `Fn` - Execute the `F` command `n` times (NOTE: `n` *may* be more than 1 digit long!)
- `Ln` - Execute `L` n times
- `Rn` - Execute `R` n times

So the example directly above can also be written as:

```
"LF5RF3RF3RF7"
```

These 5 example test cases have been included for you :)

## Kata in this Series

1. [RoboScript #1 - Implement Syntax Highlighting](https://www.codewars.com/kata/roboscript-number-1-implement-syntax-highlighting)
2. **RoboScript #2 - Implement the RS1 Specification**
3. [RoboScript #3 - Implement the RS2 Specification](https://www.codewars.com/kata/58738d518ec3b4bf95000192)
4. [RoboScript #4 - RS3 Patterns to the Rescue](https://www.codewars.com/kata/594b898169c1d644f900002e)
5. [RoboScript #5 - The Final Obstacle (Implement RSU)](https://www.codewars.com/kata/5a12755832b8b956a9000133)

```python

USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
    import resource as _res
except Exception:
    _res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
    from typing import *
except Exception:
    pass
try:
    sys.setrecursionlimit(1_000_000)
except Exception:
    pass
try:
    import site as _site
    try:
        _sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
        for _p in _sys_sites:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
    try:
        _usp = _site.getusersitepackages()
        if isinstance(_usp, str):
            _usp = [_usp]
        for _p in _usp:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
except Exception:
    pass

def _disabled_input(*args, **kwargs):
    raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input

ns = {"__name__": "__judge__"}  # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
    if not _k.startswith("_"):
        ns[_k] = _v
_CODE = 'import numpy as np\ndef switch(argument):\n    switcher = {\n        \'F\': 0,\n        \'L\': -1,\n        \'R\': 1\n    }\n    return switcher.get(argument, \'\')\n\ndef  resize(p_matrix,num,axis,dir):\n    if axis == 1:\n        right = np.zeros((p_matrix.shape[0], num))\n        left = p_matrix\n        if dir == 2:\n            right, left = left, right\n        re_matrix = np.append(left,right,axis)\n    else:\n        top = np.zeros((num,p_matrix.shape[1]))\n        bot = p_matrix\n        if dir == 1:\n            top, bot = bot, top\n        re_matrix = np.append(top,bot,axis)\n    return re_matrix\n\ndef mk_matrix(trace):\n    p_matrix = np.full((1,1),1)\n    pos = [0,0]\n    for i in range(len(trace)):\n        \n        dir = trace[i][0]\n        step = trace[i][1]\n        if step != 0 :\n            if dir == 0:\n                if (pos[1]+step+1)> p_matrix.shape[1]:\n                    p_matrix = resize(p_matrix,pos[1]+step-p_matrix.shape[1]+1,1,dir)\n                p_matrix[pos[0],(pos[1]+1):(pos[1]+step+1)] = 1\n                pos[1] = pos[1]+step\n            elif dir == 1:\n                if (pos[0]+step+1)> p_matrix.shape[0]:\n                    p_matrix = resize(p_matrix,pos[0]+step-p_matrix.shape[0]+1,0,dir)\n                p_matrix[(pos[0]+1):(pos[0]+1+step),pos[1]] = 1\n                pos[0] = pos[0]+step\n            elif dir == 2:\n                if (pos[1]-step) < 0:\n                    p_matrix = resize(p_matrix,step-pos[1],1,dir)\n                    pos[1] = step\n                p_matrix[pos[0],(pos[1]-step):(pos[1])] = 1\n                pos[1] = pos[1]-step\n            else:\n                if (pos[0]-step)<0:\n                    p_matrix = resize(p_matrix,step-pos[0],0,dir)\n                    pos[0] = step\n                p_matrix[(pos[0]-step):(pos[0]),pos[1]] = 1\n                pos[0] = pos[0]-step\n    return p_matrix\n\n\ndef tracing(path):\n    dir = 0 #pointing right\n    # 0-> direita ; 1-> baixo ; 2-> esquerda ; 3->cima\n    trace = []\n    for j in range(len(path)):\n        step = 0\n        if path[j][0] == 0:\n            if len(path[j]) == 2:\n                step = path[j][1]\n            else:\n                step = 1\n        else:\n            if len(path[j]) == 2:\n                dir = (((path[j][0]*path[j][1])+dir)%4)\n            else:\n                dir = (dir+path[j][0])%4\n        trace.append([dir,step])\n    return trace\n\ndef pathing(code):\n    path = []\n    way = -1\n    num = -1\n    for i in range(len(code)):\n        if i < num:\n            continue\n        qnt = ""\n        num = i\n        if code[i].isdecimal():\n            if num < len(code):\n                while code[num].isdecimal():\n                    qnt += code[num]\n                    if num+1 >= len(code):\n                        break\n                    num += 1\n                if len(path[way])<2:\n                    length = int(qnt,10)\n                    path[way].append(length)\n        else:\n            way+=1\n            path.append([])\n            path[way].append(switch(code[i]))\n    return path\n\ndef str_mx(matrix):\n    str = []\n    subm = np.full(matrix.shape,\' \')\n    for i in range(matrix.shape[0]):\n        for j in range(matrix.shape[1]):\n            if matrix[i][j]:\n                subm[i][j] = \'*\'\n        if i>0:\n            str.append("\\r\\n")\n        str.append(\'\'.join(subm[i]))\n    return \'\'.join(str)\n\ndef execute(code):\n    path = pathing(code)\n    trace = tracing(path)\n    matrix = mk_matrix(trace)\n    print(matrix)\n    str = str_mx(matrix)\n    return str\n'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)

_target = None
_fn_name = 'execute'
if _fn_name:
    if "Solution" in ns:
        try:
            _obj = ns["Solution"]()
            if hasattr(_obj, _fn_name):
                _target = getattr(_obj, _fn_name)
        except Exception:
            _target = None
    if _target is None and _fn_name in ns and callable(ns[_fn_name]):
        _target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
    _cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
    _user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
    if len(_user_funcs) == 1:
        _target = _user_funcs[0]
if _target is None:
    raise RuntimeError(f"Could not resolve callable '{_fn_name}'")

_raw = sys.stdin.read().strip()
if _raw:
    _parsed = json.loads(_raw)
    if isinstance(_parsed, dict):
        _kwargs = _parsed.get("kwargs", {})
        _args = _parsed.get("args", [])
    else:
        _args, _kwargs = _parsed, {}
else:
    _args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
    _args = [_args]
_res = _target(*_args, **_kwargs)
try:
    sys.stdout.write(repr(_res) + "\n")
except Exception:
    pass

```

Measured memory_bytes: 22542