Walk the words!
Dyalog APL, 63 bytes
s@(n+11 9∘○¨+\0j1*⊃¨,⍨\(8∘≠⍴¨⊢)0,'rdluRDLU'⍳¯1↓s)⍴∘'',⍨2×n←≢s←⍞
uses ⎕IO←0
and features from v16 (@
)
n←≢s←⍞
raw input s
and its length n
⍴∘'',⍨2×n
create a 2n by 2n matrix of spaces
s@(...)
amend the matrix with the characters of s
at the specified (pairs of) indices
how the indices are computed:
¯1↓s
drop the last char of s
'rdluRDLU'⍳'
encode 'r'
as 0, 'd'
as 1, etc; other chars as 8
0,
prepend a 0
(8∘≠⍴¨⊢)
turn every 8 into an empty list, all others into a 1-element list
,⍨\
cumulative swapped concatenations (abcd
-> a ba cba dcba
)
⊃¨
first from each
0j1*
imaginary constant i to the power of
+\
cumulative sums
11 9∘○¨
real and imaginary part from each; get coords in the range -n
...n
n+
centre them on the big matrix
Charcoal, 29 27 20 19 bytes
FS«F№rdlu↧ι≔ιω✳∨ωrι
Try it online! Link is to verbose version of code. Explanation:
FS«
Loop over the input characters.
F№rdlu↧ι
If the current letter is a direction...
≔ιω
then update the current walking direction.
✳∨ωrι
Print the character in the current walking direction, defaulting to right if no direction has been set yet.
C#, 525 474 Bytes
Edit: Saved 51 Bytes thanks to @steenbergh
It's not pretty, but it does work...
Golfed:
string W(string s){var l=s.Length;var a=new char[2*l+1,2*l+1];int x=2*l/2;int y=2*l/2;int d=0;for(int i=0;i<l;i++){switch(char.ToUpper(s[i])){case'U':d=3;break;case'D':d=1;break;case'L':d=2;break;case'R':d=0;break;}a[y,x]=s[i];switch(d){case 0:x+=1;break;case 1:y+=1;break;case 2:x-=1;break;case 3:y-=1;break;}}string o="";for(int i=0;i<2*l+1;i++){string t="";for(int j=0;j<2*l+1;j++)t+=a[i,j]+"";o+=t==string.Join("",Enumerable.Repeat('\0',2*l+1))?"":(t+"\r\n");}return o;}
Ungolfed:
public string W(string s)
{
var l = s.Length;
var a = new char[2 * l + 1, 2 * l + 1];
int x = 2 * l / 2;
int y = 2 * l / 2;
int d = 0;
for (int i = 0; i < l; i++)
{
switch (char.ToUpper(s[i]))
{
case 'U':
d = 3;
break;
case 'D':
d = 1;
break;
case 'L':
d = 2;
break;
case 'R':
d = 0;
break;
}
a[y, x] = s[i];
switch (d)
{
case 0:
x += 1;
break;
case 1:
y += 1;
break;
case 2:
x -= 1;
break;
case 3:
y -= 1;
break;
}
}
string o = "";
for (int i = 0; i < 2 * l + 1; i++)
{
string t = "";
for (int j = 0; j < 2 * l + 1; j++)
t += a[i, j] + "";
o += t == string.Join("", Enumerable.Repeat('\0', 2 * l + 1)) ? "" : (t + "\r\n");
}
return o;
}
Explanation:
Uses a two-dimensional array and the d
value to increment the position of the array in the correction direction, where d values are:
0 => RIGHT
1 => DOWN
2 => LEFT
3 => UP
Test:
var walkTheWords = new WalkTheWords();
Console.WriteLine(walkTheWords.W("codegolf and programming puzzles"));
cod
e
g
o
dna fl sel
z
p z
rogramming pu