# RoboScript #3 - Implement the RS2 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

Last time, you implemented the RS1 specification which allowed your customers to write more concise scripts for their robots by allowing them to simplify consecutive repeated commands by postfixing a non-negative integer onto the selected command.  For example, if your customers wanted to make their robot move 20 steps to the right, instead of typing `FFFFFFFFFFFFFFFFFFFF`, they could simply type `F20` which made their scripts more concise.  However, you later realised that this simplification wasn't enough.  What if a set of commands/moves were to be repeated?  The code would still appear cumbersome.  Take the program that makes the robot move in a snake-like manner, for example.  The shortened code for it was `F4LF4RF4RF4LF4LF4RF4RF4LF4LF4RF4RF4` which still contained a lot of repeated commands.

## Task

Your task is to allow your customers to further shorten their scripts and make them even more concise by implementing the newest specification of RoboScript (at the time of writing) that is RS2.  RS2 syntax is a superset of RS1 syntax which means that all valid RS1 code from the previous Kata of this Series should still work with your RS2 interpreter.  The only main addition in RS2 is that the customer should be able to group certain sets of commands using round brackets.  For example, the last example used in the previous Kata in this Series:


LF5RF3RF3RF7
 

... can be expressed in RS2 as:


LF5(RF3)(RF3R)F7


Or ... 


(L(F5(RF3))(((R(F3R)F7))))


Simply put, your interpreter should be able to deal with nested brackets of any level.

And of course, brackets are useless if you cannot use them to repeat a sequence of movements!  Similar to how individual commands can be postfixed by a non-negative integer to specify how many times to repeat that command, a sequence of commands grouped by round brackets `()` should also be repeated `n` times provided a non-negative integer is postfixed onto the brackets, like such:


(SEQUENCE_OF_COMMANDS)n


... is equivalent to ... 


SEQUENCE_OF_COMMANDS...SEQUENCE_OF_COMMANDS (repeatedly executed "n" times)


For example, this RS1 program:


F4LF4RF4RF4LF4LF4RF4RF4LF4LF4RF4RF4


... can be rewritten in RS2 as:


F4L(F4RF4RF4LF4L)2F4RF4RF4


Or:


F4L((F4R)2(F4L)2)2(F4R)2F4


All 4 example tests have been included for you.  Good luck :D

## 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](https://www.codewars.com/kata/roboscript-number-2-implement-the-rs1-specification)
3. **RoboScript #3 - Implement the RS2 Specification**
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)

Difficulty: interview

Starter code:

def execute(code):
	

Solutions:
from collections import deque
import re

TOKENIZER = re.compile(r'(R+|F+|L+|\)|\()(\d*)')

def parseCode(code):
    cmds = [[]]
    for cmd,n in TOKENIZER.findall(code):
        s,r = cmd[0], int(n or '1') + len(cmd)-1
        if   cmd == '(': cmds.append([])
        elif cmd == ')': lst = cmds.pop() ; cmds[-1].extend(lst*r)
        else:            cmds[-1] += [(s, r)]
    return cmds[0]

def execute(code):

    pos, dirs = (0,0), deque([(0,1), (1,0), (0,-1), (-1,0)])
    seens = {pos}
    
    for s,r in parseCode(code):
        if s == 'F':
            for _ in range(r):
                pos = tuple( z+dz for z,dz in zip(pos, dirs[0]) )
                seens.add(pos)
        else:
            dirs.rotate( (r%4) * (-1)**(s == 'R') )
    
    miX, maX = min(x for x,y in seens), max(x for x,y in seens)
    miY, maY = min(y for x,y in seens), max(y for x,y in seens)
    
    return '\r\n'.join( ''.join('*' if (x,y) in seens else ' ' for y in range(miY, maY+1)) 
                        for x in range(miX, maX+1) )

import re

def execute(code):
    def simplify_code(code):
        while '(' in code:
            code = re.sub(r'\(([^()]*)\)(\d*)',
                lambda match: match.group(1) * int(match.group(2) or 1),
                code)
        code = re.sub(r'([FLR])(\d+)',
                lambda match: match.group(1) * int(match.group(2)),
                code)
        return code

    def compute_path(simplified_code):
        pos, dir = (0, 0), (1, 0)
        path = [pos]
        for cmd in simplified_code:
            if cmd == 'F':
                pos = tuple(a + b for a, b in zip(pos, dir))
                path.append(pos)
            elif cmd == 'L':
                dir = (dir[1], -dir[0])
            elif cmd == 'R':
                dir = (-dir[1], dir[0])
        return path

    def compute_bounding_box(path):
        min_x = min(pos[0] for pos in path)
        min_y = min(pos[1] for pos in path)
        max_x = max(pos[0] for pos in path)
        max_y = max(pos[1] for pos in path)
        return (min_x, min_y), (max_x, max_y)

    def build_grid(path):
        min_xy, max_xy = compute_bounding_box(path)
        width = max_xy[0] - min_xy[0] + 1
        height = max_xy[1] - min_xy[1] + 1
        grid = [[' '] * width for _ in range(height)]
        for x, y in path:
            grid[y - min_xy[1]][x - min_xy[0]] = '*'
        return grid

    def grid_to_string(grid):
        return '\r\n'.join(''.join(row) for row in grid)

    code = simplify_code(code)
    path = compute_path(code)
    grid = build_grid(path)
    return grid_to_string(grid)

import re
from enum import Enum
from operator import itemgetter
from typing import List, Tuple, Set, Generator, Match


Cell = Tuple[int, int]


class Direction(Enum):
    UP = (0, 1)
    DOWN = (0, -1)
    RIGHT = (1, 0)
    LEFT = (-1, 0)


def execute(code: str) -> str:
    visited_cells = visit_cells(code)
    path = draw_path(visited_cells)
    return path
    
    
def visit_cells(code: str) -> Set[Cell]:
    visited_cells = [(0, 0)]
    direction = Direction.RIGHT
    
    for action, n_times in code_interpreter(code):
        if action == 'F':
            new_cells = move_forward(visited_cells[-1], direction, n_times)
            visited_cells.extend(new_cells)
        else:
            direction = make_turn(direction, action, n_times)
    return set(visited_cells)


def code_interpreter(code: str) -> Generator[Tuple[str, int], None, None]:
    code = unroll_code(code)
    for move in re.finditer(r'([LRF])(\d*)', code):
        action = move.group(1)
        n_times = int(move.group(2)) if move.group(2) else 1
        yield action, n_times
        
        
def unroll_code(code: str) -> str:
    base_command = r'[FLR]\d*'
    composed = fr'\((?P<command>({base_command})+)\)(?P<repeat>\d*)'
    
    while True:
        prev_code = code
        code = re.sub(composed, unroll_command, prev_code)
        if code == prev_code:
            break
    return code

def unroll_command(match: Match) -> str:
    repeat = int(match['repeat']) if match['repeat'] else 1
    return match['command'] * repeat
    

def move_forward(position: Cell, direction: Direction, n_moves: int) -> List[Cell]:
    px, py = position
    dx, dy = direction.value
    return [(px + i * dx, py + i * dy) for i in range(1, n_moves + 1)]


def make_turn(start: Direction, side: str, n_turns: int) -> Direction:
    ordering = [Direction.RIGHT, Direction.DOWN, Direction.LEFT, Direction.UP]
    step = 1 if side == 'R' else -1
    return ordering[(ordering.index(start) + step * n_turns) % len(ordering)]
    
    
def draw_path(visited_cells: Set[Cell]) -> str:
    max_x, min_x, max_y, min_y = find_cells_boundaries(visited_cells)
    
    rectangle = list()
    for y in range(max_y, min_y - 1, -1):
        row = ['*' if (x, y) in visited_cells else ' ' for x in range(min_x, max_x + 1)]
        rectangle.append(''.join(row))
    
    return '\r\n'.join(rectangle)
    
    
def find_cells_boundaries(visited_cells: Set[Cell]) -> Tuple[int, int, int, int]:
    max_x, _ = max(visited_cells, key=itemgetter(0))
    min_x, _ = min(visited_cells, key=itemgetter(0))
    
    _, max_y = max(visited_cells, key=itemgetter(1))
    _, min_y = min(visited_cells, key=itemgetter(1))
    return max_x, min_x, max_y, min_y


def execute(code):
    R, r, c, dr, dc = {(0, 0)}, 0, 0, 0, 1
    D = {(1, 0):{'R':(0, -1), 'L':(0, 1)}, (-1, 0):{'R':(0, 1), 'L':(0, -1)}, (0, 1):{'R':(1, 0), 'L':(-1, 0)}, (0, -1):{'R':(-1, 0), 'L':(1, 0)}}
    
    while ')' in code:
        for i, v in enumerate(code):
            if v == '(': lastopen = i
            if v == ')':
                n, k = '', i + 1
                while code[k:k+1].isdigit(): 
                    n, k = n + code[k], k + 1                
                code = code[:lastopen] + code[lastopen+1:i] * int(n or '1') + code[k:]
                break

    for cmd in code.replace('R', ' R').replace('L', ' L').replace('F', ' F').strip().split():
        cmd, n = cmd[:1], int(cmd[1:]) if cmd[1:] else 1
        for _ in range(n):
            if cmd in 'RL':             
                dr, dc = D[(dr, dc)][cmd]
            else:
                r, c = r + dr, c + dc
                R.add((r, c))
                
    mnr, mnc = min(r for r, _ in R), min(c for _, c in R)

    R = {(r - mnr, c - mnc) for r, c in R}
    
    mxr, mxc = max(r for r, _ in R), max(c for _, c in R)           
    
    return '\r\n'.join(''.join(' *'[(r, c) in R] for c in range(mxc+1)) for r in range(mxr+1))

import re
from collections import defaultdict, deque
def execute(code):
    dirs = deque([(0, 1), (-1, 0), (0, -1), (1, 0)])
    yarr, xarr = [0], [0]
    while True:
        code, n = re.subn('\(([^()]+)\)(\d*)', lambda m: m.group(1) * int(m.group(2) or 1), code)
        if not n:
            break
    for c in ''.join(a * int(b or 1) for a, b in re.findall('(\D)(\d*)', code)):
        if c == 'F':
            dy, dx = dirs[0]
            xarr.append(xarr[-1] + dx)
            yarr.append(yarr[-1] + dy)
        if c == 'L':
            dirs.rotate(-1)
        if c == 'R':
            dirs.rotate(1)
    xmin, xmax = min(xarr), max(xarr)
    ymin, ymax = min(yarr), max(yarr)
    d = dict(zip(zip(yarr, xarr), '*' * len(xarr)))
    return '\r\n'.join(''.join(d.get((y, x), ' ') for x in range(xmin, xmax + 1)) for y in range(ymin, ymax + 1))

from typing import Tuple, Optional, Union, Any, List, Dict, Callable, Iterator
from enum import Enum, auto
import re

OptFunc = Optional[Callable[[], Any]]

instructions_pattern = re.compile(r'F+\d*|L+\d*|R+\d*')


class BufferedIterator:
    _iter: Iterator[str]
    _stack: List[str]

    def __init__(self, it: Iterator[str]):
        self._iter = it
        self._stack = []

    def __iter__(self):
        return self

    def __next__(self):
        if self._stack:
            return self._stack.pop()
        else:
            return next(self._iter)

    def push(self, s):
        self._stack.append(s)


class StringBuf:
    _text: str

    def __init__(self, s: Optional[str] = None):
        self._text = s or ''

    def __str__(self):
        return self._text

    def __repr__(self):
        return f'StringBuf({self._text!r})'

    def append(self, s: str):
        self._text += s

    def prepend(self, s: str):
        self._text = s + self._text

    def __getitem__(self, idx):
        return self._text[idx]

    def __setitem__(self, idx, value):
        if isinstance(idx, int):
            self._text = self._text[:idx] + value + self._text[(idx + len(value)):]


class Rotation(Enum):
    No = auto()
    Left = auto()
    Right = auto()

    def switch(self, right: OptFunc = None, left: OptFunc = None, none: OptFunc = None) -> Any:
        if self is self.Right:
            if right is not None:
                return right()
        elif self is self.Left:
            if left is not None:
                return left()
        elif self is self.No:
            if none is not None:
                return none()

        return None


class Direction(Enum):
    Up = 0
    Right = 1
    Down = 2
    Left = 3

    @staticmethod
    def from_num(count: int) -> 'Direction':
        return Direction((4 - (-count % 4)) % 4 if count < 0 else count % 4)

    def to_num(self) -> int:
        return self.value

    def switch(self, up: OptFunc = None, right: OptFunc = None, down: OptFunc = None, left: OptFunc = None) -> Any:
        if self is self.Up:
            if up is not None:
                return up()
        elif self is self.Right:
            if right is not None:
                return right()
        elif self is self.Down:
            if down is not None:
                return down()
        elif self is self.Left:
            if left is not None:
                return left()

        return None

    def next(self, pos: Tuple[int, int], count: int) -> Tuple[int, int]:
        return self.switch(
            up=lambda: (pos[0], pos[1] - count),
            right=lambda: (pos[0] + count, pos[1]),
            down=lambda: (pos[0], pos[1] + count),
            left=lambda: (pos[0] - count, pos[1]),
        )

    def change(self, rot: Rotation, count: int) -> 'Direction':
        return rot.switch(
            left=lambda: Direction.from_num(self.to_num() - count),
            right=lambda: Direction.from_num(self.to_num() + count),
            none=lambda: self,
        )


class TheGridForTron:
    _grid: List[StringBuf]
    _size: int
    _org: Tuple[int, int]
    _pos: Tuple[int, int]
    _dir: Direction

    def __init__(self):
        self._grid = [StringBuf('*')]
        self._size = 1
        self._org = (0, 0)
        self._pos = (0, 0)
        self._dir = Direction.Right

    def _grow(self):
        # Grow to left
        diff = self._org[0] - self._pos[0]
        if diff > 0:
            self._org = (self._pos[0], self._org[1])
            self._size += diff

            s = ' ' * diff

            for line in self._grid:
                line.prepend(s)

            return

        # Grow to up
        diff = self._org[1] - self._pos[1]
        if diff > 0:
            self._org = (self._org[0], self._pos[1])

            s = ' ' * self._size
            for _ in range(diff):
                self._grid.insert(0, StringBuf(s))

            return

        # Grow to right
        diff = self._pos[0] - (self._org[0] + self._size) + 1
        if diff > 0:
            s = ' ' * diff

            self._size += diff
            for line in self._grid:
                line.append(s)

            return

        # Grow to down
        diff = self._pos[1] - (self._org[1] + len(self._grid)) + 1
        if diff > 0:
            s = ' ' * self._size
            for _ in range(diff):
                self._grid.append(StringBuf(s))

    def _trace_path(self, old: Tuple[int, int]):
        def up():
            pos = self._pos[0] - self._org[0]
            org = self._org[1]

            for line in self._grid[(self._pos[1] - org):(old[1] - org)]:
                line[pos] = '*'

        def right():
            self._grid[self._pos[1] - self._org[1]][old[0] + 1 - self._org[0]] = '*' * (self._pos[0] - old[0])

        def down():
            pos = self._pos[0] - self._org[0]
            org = self._org[1]

            for line in self._grid[(old[1] + 1 - org):(self._pos[1] + 1 - org)]:
                line[pos] = '*'

        def left():
            self._grid[self._pos[1] - self._org[1]][self._pos[0] - self._org[0]] = '*' * (old[0] - self._pos[0])

        self._dir.switch(
            up=up,
            right=right,
            down=down,
            left=left,
        )

    def do_move(self, rot: Rotation, count: int):
        if rot is Rotation.No:
            old = self._pos

            self._pos = self._dir.next(self._pos, count)
            self._grow()
            self._trace_path(old)
        else:
            self._dir = self._dir.change(rot, count)

    def serialize(self) -> str:
        return '\r\n'.join(map(str, self._grid))


class Executor:
    _grid: TheGridForTron
    _actions: Dict[str, Callable[[int], Any]]

    def __init__(self, grid: TheGridForTron):
        self._grid = grid
        self._actions = {
            'F': lambda cnt: self._grid.do_move(Rotation.No, cnt),
            'L': lambda cnt: self._grid.do_move(Rotation.Left, cnt),
            'R': lambda cnt: self._grid.do_move(Rotation.Right, cnt),
        }

    def do_actions(self, code: str):
        for m in instructions_pattern.finditer(code):
            action, count = parse_instruction(m.group())

            self._actions.get(action, lambda _: None)(count)


def expand_code(code: BufferedIterator) -> str:
    res: str = ''
    sub_str: str = ''
    in_group: bool = False
    count: Union[None, int] = None

    for ch in code:
        if in_group:
            try:
                count = ((count or 0) * 10) + int(ch)
            except ValueError:
                code.push(ch)
                if count is not None:
                    sub_str *= count
                    count = None

                res += sub_str
                sub_str = ''
                in_group = False
        else:
            if ch == ')':
                break

            if ch == '(':
                sub_str = expand_code(code)
                in_group = True
                continue

            res += ch

    if sub_str:
        if count is not None:
            sub_str *= count

        res += sub_str

    return res


def parse_instruction(code: str) -> Tuple[str, int]:
    c = code[0]

    count = code.lstrip(c)
    n = len(code) - len(count)

    if count:
        n += int(count) - 1

    return c, n


def execute(code: str) -> str:
    grid = TheGridForTron()

    Executor(grid).do_actions(expand_code(BufferedIterator(iter(code))))

    return grid.serialize()


def execute(code):
    path = translatePath(createPath(transformCode(removeBrackets(code))))
    if path == "":
        return "*"
    xmax = 0
    ymax = 0
    for coordinate in path:
        if coordinate[0] > xmax:
            xmax = coordinate[0]
        if coordinate[1] > ymax:
            ymax = coordinate[1]
    grid = []
    for something in range(ymax+1):
        grid.append((xmax + 1) * [' '])
    for visited in path:
        grid[visited[1]][visited[0]] = '*'
    finalstring = ""
    for row in grid:
        for elem in row:
            finalstring += elem
        finalstring += "\r\n"    
    return finalstring[:-2]
def removeBrackets(rscommand):
    # check for brackets
    if rscommand.find('(') == -1:
        return rscommand
    found = False
    indeks = 0
    openbracketindex = 0
    closingbracketindex = 0
    while not found and indeks < len(rscommand):
        if rscommand[indeks] == '(':
            openbracketindex = indeks
        if rscommand[indeks] == ')':
            closingbracketindex = indeks
            found = True
        indeks += 1
    leftpart = rscommand[:openbracketindex]
    rightpart = rscommand[closingbracketindex + 1:]
    middlepart = rscommand[openbracketindex+1:closingbracketindex]
    
    #find number in rightpart
    factor = ""
    indeks = 0
    if len(rightpart) > 0:
        while rightpart[indeks].isdigit():
            factor += rightpart[indeks]
            indeks += 1
            if indeks == len(rightpart):
                break    
    
    if indeks > 0:
        newcommand = leftpart + int(factor)* middlepart + rightpart[indeks:]
    else:
        newcommand = leftpart + middlepart + rightpart
    return removeBrackets(newcommand)
def createPath(command):
    state = [0,0,"E"]
    path = [[0,0]]
    for x in command:
        if x == 'L' or x == 'R':
            state = makeTurn(state,x)
        else:
            state = moveForward(state)
            path.append([state[0],state[1]])
    
    return path
def translatePath(path):
    minx = 0
    miny = 0
    for c in path:
        if c[0] < minx:
            minx = c[0]
        if c[1] < miny:
            miny = c[1]
    #translate path
    for c in path:
        c[0] = c[0] - minx
        c[1] = c[1] - miny
    return path 
def moveForward(state):
    #state[0] = x coordinate
    #state[1] = y coordinate
    #state[2] = direction N, S, E or W
    if state[2] == "N":
        return [state[0],state[1]-1,state[2]]
    if state[2] == "S":
        return [state[0],state[1]+1,state[2]]
    if state[2] == "W":
        return [state[0]-1,state[1],state[2]]
    # remaing direction is east_asian_width
    return [state[0]+1,state[1],state[2]]
def makeTurn(state,leftorright):
    if leftorright == "L":
        if state[2] == "N" :
            return [state[0],state[1], "W"]
        if state[2] == "W" :
            return [state[0],state[1], "S"]
        if state[2] == "S" :
            return [state[0],state[1], "E"]
        if state[2] == "E" :
            return [state[0],state[1], "N"]
    if leftorright == "R":
        if state[2] == "N" :
            return [state[0],state[1], "E"]
        if state[2] == "W" :
            return [state[0],state[1], "N"]
        if state[2] == "S" :
            return [state[0],state[1], "W"]
        if state[2] == "E" :
            return [state[0],state[1], "S"]
def transformCode(code):
    newcode = ""
    indeks = 0
    while indeks < len(code):
        while not code[indeks].isdigit():
            newcode += code[indeks]
            indeks += 1
            if indeks == len(code):
                break
        if indeks == len(code):
                break
        #found a digit
        factor = ""
        while code[indeks].isdigit():
            factor += code[indeks]
            indeks += 1
            if indeks == len(code):
                break
        newcode = newcode[:-1] + int(factor) * newcode[-1]
    return newcode

from collections import deque
import re
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])

RIGHT = 0
UP = 1
LEFT = 2
DOWN = 3

DIRECTIONS = [
    Point(1, 0),
    Point(0, -1),
    Point(-1, 0),
    Point(0, 1),
]

FORWARD = 1
BACKWARD = -1

def generate_jump_map(code):
    jump_map = {}
    
    opening_bracket_stack = deque()
    
    for i, c in enumerate(code):
        if c == '(':
            opening_bracket_stack.append(i)
        elif c == ')':
            opening_index = opening_bracket_stack.pop()
            jump_map[i] = opening_index
            jump_map[opening_index] = i
    
    return jump_map

execution_count_pattern = re.compile(r"\d*")

def code_unwrap(code):
    jump_map = generate_jump_map(code)
    
    def code_unwrap_inner(code, ip, end_address):
        while ip < end_address:
            execution_count_str = execution_count_pattern.match(code[ip+1:]).group(0)
            execution_count = int(execution_count_str or "1")
            
            for _ in range(execution_count):
                if code[ip] == ')':
                    # Recursively unwrap the inner part
                    yield from code_unwrap_inner(code, jump_map[ip] + 1, ip)
                elif code[ip] == '(':
                    # Jump to the end to find out how often it has to run
                    ip = jump_map[ip] - 1
                else:
                    yield code[ip]
            ip += 1 + len(execution_count_str)
                
    yield from code_unwrap_inner(code, 0, len(code))

def execute(code):
    visited = {Point(0, 0)}
    pos = Point(0, 0)
    direction = RIGHT
    
    def get_area():
        xmin = 2**30
        xmax = -2**30
        ymin = 2**30
        ymax = -2**30
        
        for x, y in visited:
            xmin = min(xmin, x)
            xmax = max(xmax, x)
            ymin = min(ymin, y)
            ymax = max(ymax, y)
        
        return xmin, xmax, ymin, ymax
    
    for c in code_unwrap(code):
        if c == 'F':
            delta = DIRECTIONS[direction]
            pos = Point(pos.x + delta.x, pos.y + delta.y)
            visited.add(pos)
        elif c == 'L':
            direction = (direction + 1) % 4
        elif c == 'R':
            direction = (direction - 1) % 4
    
    xmin, xmax, ymin, ymax = get_area()
    
    ret = '\r\n'.join(
        ''.join(
            '*' if (x, y) in visited else ' '
            for x in range(xmin, xmax+1)
        )
        for y in range(ymin, ymax+1)
    )
    # print(ret)
    return ret
            
    
    


def execute(code):
    x, y = 0, 1
    direction = 1
    visited = {(x, y)}
    loops = []
    i = 0
    while i < len(code):
        c = code[i]
        i += 1
        if c == '(':
            j = i
            p = 1
            while p:
                if code[j] == '(': p += 1
                elif code [j] == ')': p -= 1
                j += 1
            k = j
            while k < len(code) and code[k].isdigit(): k += 1
            reps = int(code[j:k]) if k > j else 1
            if reps == 0:
                i = k
                continue
            loops.append((i, reps-1))
        elif c == ')':
            start, reps = loops.pop()
            if reps:
                loops.append((start, reps-1))
                i = start
        elif c not in 'FLR': raise RuntimeError(f'Unknown command: {c}')
        j = i
        while i < len(code) and code[i].isdigit():
            i += 1
        steps = int(code[j:i]) if i > j else 1
        if c == 'F':
            for _ in range(steps):
                x += dx[direction]
                y += dy[direction]
                visited.add((x, y))
        elif c == 'R': direction = (direction + steps) % 4
        elif c == 'L': direction = (direction - steps) % 4
    min_x = min(x for x, y in visited)
    min_y = min(y for x, y in visited)
    width = max(x for x, y in visited) - min_x + 1
    height = max(y for x, y in visited) - min_y + 1
    grid = [[' '] * width for _ in range(height)]
    for x, y in visited: grid[y-min_y][x-min_x] = '*'
    return '\r\n'.join(''.join(row) for row in grid)

dx = 0, 1, 0, -1
dy = -1, 0, 1, 0


from re import findall

dirs = { 0: (1, 0), 1: (0, 1), 2: (-1, 0), 3: (0, -1)}

def find_sub(tokens):
    start = None
    for i in range(len(tokens)):
        if tokens[i] == '(':
            start = i
        elif tokens[i][0] == ')':
            return (start, i)

def execute(code):
    tokens = findall('(\(|[FRL)]|[0-9]+)', code)
    
    def opt(flat):
        while '0' in flat:
            index = flat.index('0')
            del flat[index-1:index+1]
        return flat
    
    while '(' in tokens:
        start, end = find_sub(tokens)
        sub = tokens[start+1:end]
        del tokens[start+1:end+1]
        tokens[start] = opt(sub)
    tokens = opt(tokens)
    
    path, loc, dire = [(0, 0)], (0, 0), 0

    def perform(op):
        nonlocal path, loc, dire
        if type(op) == list:
            return perform_list(op)
        if op == 'F':
            loc = (loc[0] + dirs[dire][0], loc[1] + dirs[dire][1])
            path.append(loc)
        else:
            d = 1 if op == 'R' else -1
            dire = (dire + d) % 4
    
    def perform_list(list):
        last = None
        for i in list:
            if type(i) == str and i.isdigit():        
                for _ in range(int(i)-1):
                    perform(last)
            else:
                perform(i)
                last = i
    
    perform_list(tokens)

    minx = min(i[0] for i in path)
    maxx = max(i[0] for i in path)
    miny = min(i[1] for i in path)
    maxy = max(i[1] for i in path)
    
    w, h = (maxx - minx + 1), (maxy - miny + 1)
    map = [[' ' for _ in range(w)] for _ in range(h)]
    
    for i in path:
        map[i[1]-miny][i[0]-minx] = '*'
    
    return '\r\n'.join(''.join(i) for i in map)