17
2
Write a program or function that takes in a nonempty single-line string of printable ascii characters excluding space:
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
You may assume the input is valid.
Based on the input, draw a new string arranged on a textual grid of spaces and newlines following turtle graphics-esque rules where the turtle always occupies one grid space and can only face the cardinal directions.
Print the first character in the input string to the text grid. The turtle starts here facing right. Iterate over the rest of the characters in the input string (only stopping if the turtle gets stuck), repeating this process:
If the 4 grid spaces directly neighboring the turtle are all filled (i.e. none of them is a space), stop iterating. The turtle is stuck and the grid is as complete as it can be.
Look at the current character in the input compared to the previous character:
If the current character is lexically before the previous, rotate the turtle a quarter turn left.
If the current character is lexically after the previous, rotate the turtle a quarter turn right.
If the current character equals the previous, don't rotate the turtle.
If the grid space the turtle is now facing is not empty (i.e. not a space), repeatedly rotate the turtle a quarter turn left until she is facing an empty grid space.
Move the turtle one grid step forward in the direction she's facing and print the current character on the grid in the turtle's new location.
Print or return the resulting text grid string with no extraneous rows or columns of whitespace. Lines may have trailing spaces up to the rightmost column with a non-space, but not beyond. A single trailing newline is optionally allowed.
The shortest code in bytes wins.
Example
Here are all the steps of the input spattuuxze
. The ^V<>
characters show the direction the turtle is facing, they are not part of the input or output.
s>
^
p
s
<ap
s
^
t
ap
s
^
t
t
ap
s
tu>
t
ap
s
tuu>
t
ap
s
tuu
t x
apV
s
tuu
<zx
ap
s
At this point the turtle is stuck so the e
never gets printed and the final output is:
tuu
tzx
ap
s
Following is a similar but invalid output since it has an unnecessary leading column of whitespace:
tuu
tzx
ap
s
Test Cases
spattuuxze
tuu
tzx
ap
s
spattuuxxze
tuu
t x
apx
sze
1111111
1111111
ABCDEFGHIJKLMNOP
PEFG
ODAH
NCBI
MLKJ
`_^]\[ZYXWVUTSR
^_RS
\]`UT
[ZWV
YX
Woo!
W
o
o!
woo!
!o
o
w
Wheeee
W
heeee
banana
a
an
an
b
Turtle
T
ure
tl
turTle
e
tTl
ur
(Do tell me right away if any of these seem wrong.)
You weren't kidding. – R. Kap – 2016-08-02T09:08:25.387
I think you should add the test case
PONMLKJIHGFEDCBA
, since the result is not just a square and contrasts withABCDEFGHIJKLMNOP
to highlight the asymmetry in the rules. – Greg Martin – 2016-10-12T23:06:15.340