20
\$\begingroup\$

The beloved fish who swims through the code of ><> (an esoteric programming language) has been taken out of its natural environment. This change has rendered it incapable of moving around in the way it's used to: what used to be toroidal movement has been restricted to simple left-to-right movement. But ><> programs are still written as if the fish were capable of moving through them. It is your task, dear programmer, to write a program to linearize a ><> program. And do it in as few bytes as possible; fish don't have very large memories.

Movement in ><>

In ><>, movement is toroidal and one character at a time. This means that the fish (the pointer) can "wrap" around from the end of a line back to the beginning. In ><>, the fish also is capable of moving top-to-bottom, bottom-to-top, and right-to-left, in contrast to the way most pointers move. So this movement pattern would be valid:

>>>^  >>>v
   >>>^  v

and it would end on an infinite loop (looping back to the top line once it gets past the bottom infinitely).

The fish moves in a grid of length equal to max(row length) and height equal to the number of rows.

How do you figure out which way the fish moves? These commands change the direction vector of movement (e.g. (-1,0) means right-to-left):

Command | Direction Change
---------------------------
   >    | (1,0) (default)
   <    | (-1,0)
   ^    | (0,1)
   v    | (0,-1)
   /    | (x,y) -> (y,x)
   \    | (x,y) -> (-y,-x)
   |    | (x,y) -> (-x,y)
   _    | (x,y) -> (x,-y)
   #    | (x,y) -> (-x,-y)
   ;    | (0,0)

As noted, the fish starts moving left-to-right, i.e. with direction vector (1,0). The fish starts parsing commands starting with the first command it sees and changes its direction if a command matches one of the aforementioned direction changers.

The fish stops moving when it sees a ; and terminates the program.

Input

Input will be a valid (e.g. not infinitely looping) program given through STDIN. You may also read a file if you wish. The lines of each program will not necessarily be of the same length.

Input is given as a string, with newlines separating each line in the program.

Programs will not loop, which also means they will always terminate with a ;.

Output

Output will be the program linearized. That is, you should return all of the characters (including direction changers) that the fish would see if it ran the program "normally." This is all of the characters in its path to the ;.

If the input is has lines of unequal length and the fish ends up moving along a line shorter than the length of the longest line, you should treat that as if the fish were moving over a space (see test cases).

Those familiar with ><> will know that direction changers are not the only way to do movement in it, but for simplicity's sake treat the input as if they are the only way to affect movement.

Rules

  1. Standard loopholes apply
  2. You may write either a full program or function
  3. Input is supplied through STDIN or a file as a string containing the program lines separated by newlines (\n)
    • You may take the input differently, within reason (feel free to ask me if you have a specific kind of input in mind). You may not pad the input with spaces so the line lengths match.
    • Refer to this meta post regarding flexible input. As it stands of posting, general consensus is to be as flexible as possible within reason.
  4. Output is a single string through STDOUT or returned by the function (depending on what you choose to do, see Rule 2)

Test Cases

v     >v
>abcv//;
gfed<^ih

v>abcv<defghi^//>v;



v     >v
>abcv//;
gfed<^

v>abcv<defg  ^//>v;


abcdef;

abcdef;


abcd|;

abcd|dcba;


abcd#;

abcd#dcba;


abcd\;
    _

abcd\_\dcba;


^;
>abcde/
 ^jihg<

^ >abcde/ <ghij^a;


;

;
\$\endgroup\$
  • 2
    \$\begingroup\$ Can we take the input as an array of strings? \$\endgroup\$ – Luke Mar 26 '17 at 12:00
  • 2
    \$\begingroup\$ Can we assume that the first character (the top left one) won't be a semicolon? \$\endgroup\$ – Kritixi Lithos Mar 26 '17 at 13:04
  • 1
    \$\begingroup\$ @KritixiLithos good question, I'm going to say you can't assume that. I'll add a test case. \$\endgroup\$ – cole Mar 26 '17 at 16:14
  • 1
    \$\begingroup\$ @Luke you may take the input as an array of strings if it is either very hard or impossible to operate on the input format (string with lines separated by newlines). See the now-added Rule 3. \$\endgroup\$ – cole Mar 26 '17 at 16:36
  • 3
    \$\begingroup\$ Obligatory upvote for absurd rationale \$\endgroup\$ – Patrick Roberts Mar 31 '17 at 16:39
13
\$\begingroup\$

Röda, 405 393 392 391 371 366 361 236 234 232 230 223 200 bytes

F f{L=f()|[#_]|sort|tail
c=""x=0
y=0
X=1
Y=0{l=f[y]l.=[" "]*(L-#l)c=l[x]a=X
[c]
C=indexOf(c,`><v^/\|_#`)X=[1,-1,0,0,-Y,Y,-X,X,-X,X][C]Y=[0,0,1,-1,-a,a,Y,-Y,-Y,Y][C]x+=X
x=x%L
y+=Y
y=y%#f}until[c=";"]}

Try it online!

Check outputs!

Explanation (outdated)

F f{                          /* Declares a function F with parameter f */
                              /* Takes a 2D array of single-char Strings as f */
L =                           /* L contains the value of the length of the longest line*/
    f()                       /* Push the contents each element of f to the stream; this pushes each line*/
        | [#_]                /* Pull a line and push its length to the stream*/
               |sort|tail     /* Sort it and get the last value (the largest one) */
c=""                          /* c contains the value of the current char that is being processed */
x=0; y=0                      /* x and y contain the position of the fish */
X=1; Y=0                      /* X and Y contain the direction of the fish */
{ ... }while [c != ";"]       /* While c is not `;` do: */
l=f[y]                        /*  l is the line (row) the fish is at */
c=" " if [x >= #l]            /*  If x is more than or equal to the line's length, set c to a space (so that we don't need to pad spaces to the array at the beginning)*/
else c = l[x]                 /*  Else set c to the character a position x of l*/
[c]                           /*  Push c to the output stream; ie prints c without a trailing newline*/
a = X                         /*  a preserves the value of X before analysing c */
C = indexOf(c,`><v^/\|_#`)    /*  Simple enough */
X=[1,-1,0,0,-Y,Y,-X,X,-X,X][C]/*  Map each value of C to their respective X-direction in the array */
                              /*  If c cannot be found in `><v^/\|_#` then it will be given the value of -1, or in other words, the -1th element of an array its last element */
Y=[0,0,1,-1,-a,a,Y,-Y,-Y,Y][C]/*  Do the same thing for Y */
x += X                        /*  Change the x-pos by the X-direction */
x = x%L                       /*  Wrap around the right edge */
y += Y                        /*  Do the same for y */
y=y%#f                        /*  But wrap around the bottom instead */
x+=L if[x<0]                  /*  Wrap around the left */
y+=#f if[y<0]                 /*  Wrap around the top */
}

Edits

  • 10 bytes saved thanks to @fergusq by using % instead of checking whether x or y is over the boundaries, which paved the way for 2 more!
  • Used `\` instead of "\\"
  • Moved c="" to the second line and then removed the newline following it
  • Moved the conversion of the lines to single-character array into the loops instead of at the beginning (inspired by the Python answer)
  • Used the brace syntax of while (thanks to @fergusq for spotting that)
  • Moved the a=X out of the if-statements
  • Thanks to @fergusq for finding a shorter way to find the length of the longest line
  • Used array syntax instead of if-statements (like the Python answer) to save tons of bytes
  • Removed the code that padded spaces, instead spaces are added as the ><> moves along
  • Fixed a bug thanks and golfed one character thanks to @fergusq
  • Removed the +1 at the end of indexOf and restructured code to save 2 bytes
  • Saved 2 bytes by moving things around (thanks to @fergusq again)
  • Saved 1 byte thanks to @fergusq by using a different method of padding spaces
  • Saved 1 byte by using until[c=";"] instead of while[c!=";"]
  • Thanks to a hint from @fergusq, I removed the loop that pads spaces and replaced it with l.=[" "]*L
  • Saved over 20 bytes by removing the if-statements at the end that wrap the program around the left and top edges
\$\endgroup\$
  • \$\begingroup\$ I think you can save a few bytes by using x=((x+X)%#l) instead of x+=X. Unfortunately, (-1)%#l still returns -1. \$\endgroup\$ – fergusq Mar 26 '17 at 17:20
  • \$\begingroup\$ @fergusq Golfed your suggestion :) \$\endgroup\$ – Kritixi Lithos Mar 26 '17 at 17:51
  • \$\begingroup\$ You can use it with y too: y=y%#f. \$\endgroup\$ – fergusq Mar 26 '17 at 17:55
  • \$\begingroup\$ @fergusq Was just about to add that :) \$\endgroup\$ – Kritixi Lithos Mar 26 '17 at 17:56
  • \$\begingroup\$ I thought about this more, here are two other golfing tips: use key instead of cmp and use {...}while[...] instead of while[...]do ... done. \$\endgroup\$ – fergusq Mar 27 '17 at 8:49
10
\$\begingroup\$

Python 2, 262 243 237 235 234 233 231 221 219 218 217 bytes

Takes input as ['<line_1>', '<line_2>', ...]

i=input()
q=max(map(len,i))
i=[k+' '*q for k in i]
x=y=k=0
j=1
o=''
while';'not in o:r=[1,-1,-j,-k,0,0];o+=i[y][x];l='><#\\v^/|_'.find(o[-1]);a=(r+[k,-j,j])[l];k=([k,-k,k,j]+r)[~l];j=a;x=(x+j)%q;y=(y-k)%len(i)
print o

Try it Online!

-19 bytes thanks to @math_junkie
-6 bytes thanks to @ThisGuy
-2 bytes by extracting max(map(L,i)) to a variable (because it is theoretically used twice).
-1 byte by reducing the number of times i[y][x] shows up.
-1 byte by using '\x00' so I don't have to do the [1:] part of o[1:] in the output
-2 bytes by using \0 instead of \x00
-10 bytes thanks to @KritixiLithos for realizing that I can pad as much as I want on the right side because the extra will be ignored
(no byte change) fixed bug because extracted variable was outside of loop
-2 bytes because now I only use len 2 times so reassigning it takes 2 additional bytes
-2 byte by using while';'not in o instead of while o[-1]!=';', and using o='' instead of o='\0'. This not only saves 2 bytes but also gets rid of the leading null byte which was technically not really valid.

Explanation

i = input()                       # Takes input as an array of strings
q = max(map(len,i))               # Finds the width of the longest line
i = [k + ' ' * q for k in i]      # Makes sure everything is at least that width
x = y = k = 0                     # Set the point to (0, 0). Set the vertical motion to 0
j = 1                             # Set the horizontal motion to 1
o = '\0'                          # Initialize the output to a null byte (this is output as nothing, so it doesn't actually affect output)
while o[-1] != ';':               # While the last character in the output is not ';' (this is why the output needs to be initialized with something, otherwise o[-1] gives an index error)
    r = [1,-1,-j,-k,0,0]          # Some of the vertical and horizontal coordinates correspond in opposite order
    o += i[y][x]                  # Add the current character to the output
    l = '><#\\v^/|_'.find(o[-1])  # Find the index of the current character here (or -1 if it's just a regular character)
    a = (r + [k, -j, j])[l]       # The fancy array contains the horizontal movement for each control character
    k = ([k, -k, k, j] + r)[~l]   # The fancy array contains the vertical movement for each control character. Using ~l to get the right index, because r has the values backwards
    j = a                         # a was a placeholder because otherwise k would not be correct
    x = (x + j) % q               # Adjust the pointer position
    y = (y - k) % len(i)          # Adjust the pointer position
print o                           # Print the output after the loop is finished
\$\endgroup\$
  • \$\begingroup\$ You can golf off the try since find returns -1 if not found : TIO \$\endgroup\$ – math junkie Mar 27 '17 at 14:15
  • \$\begingroup\$ @math_junkie Oh okay, thanks! \$\endgroup\$ – HyperNeutrino Mar 27 '17 at 14:25
  • \$\begingroup\$ You can assign len to a variable e.g L to save 3 bytes and another 4 by changing the multiline assignment to 0 into 1 line x=y=k=0. \$\endgroup\$ – caird coinheringaahing Mar 27 '17 at 14:31
  • \$\begingroup\$ @ThisGuy Thanks! \$\endgroup\$ – HyperNeutrino Mar 27 '17 at 14:33
  • 2
    \$\begingroup\$ @Cole In my suggeted golf, I added j and k to the end of each array. This is so the direction is maintained \$\endgroup\$ – math junkie Mar 27 '17 at 14:41
5
\$\begingroup\$

Ruby, 274 200 187 183

Shaved off just a few more characters by dropping the momentum array, d.

I'm pretty proud of this one. This was fun! It takes in an array of strings and returns the proper string.

->a{o,x,y='',-1,0
b,m=1,0
(o+=n=a[y=(y+m)%a.size][x=(x+b)%(a.map &:size).max]||' '
b,m=([1]+[0,-1,0]*2+[1,-m]+[-b,m,b]*2+[-m,-b,-m,b,m])[2*('><^v/\\|_#'.index(n)||9),2])until o[?;]
o}

Commented below.

->a{
    o,x,y='',-1,0  # o is the output string, x and y are the positions in the array
    b,m=1,0          # b and m are the direction of momentum
    until o[?;] # until o contains a semicolon
        w=(a.map &:size).max # w is the max width of the arrays
        h=a.size    # h is the height of arrays
        x=x+b % w   # increment cursor position
        y=y+m % h
        o+=n=a[y][x]||' ' # add the new char (or " ") to o
        ix=2*('><^v/\\|_#'.index(n)||9) # find the index new char in the string
        b,m=([1]+[0,-1,0]*2+[1,-m]+[-b,m,b]*2+[-m,-b,-m,b,m])[ix,2] # set momentum to its new value
    end
    o # return output string
}
\$\endgroup\$
1
\$\begingroup\$

PHP 7, 291 260 bytes

for($m=max(array_map(strlen,$z=explode("
",$argv[1]))),$y=0,$r=count($z)-$v=1;';'!=$c;[$v,$w]=[[$v,1,-1,0,0,-$w,$w,-$v,$v,-$v][$o=strpos(' ><^v/\|_#',$c)],[$w,0,0,-1,1,-$v,$v,$w,-$w,-$w][$o]],$x+=$m+$v,$x%=$m,$y=0<=($y+=$w)?$r<$y?:$y:$r)echo$c=$z[$y][$x]??' ';
\$\endgroup\$
  • \$\begingroup\$ I count 291 bytes/chars. \$\endgroup\$ – HyperNeutrino Mar 28 '17 at 16:56
  • \$\begingroup\$ You're correct, I fail at counting apparently =P \$\endgroup\$ – chocochaos Mar 28 '17 at 18:14
  • \$\begingroup\$ Hah Don't worry, I did that too. \$\endgroup\$ – HyperNeutrino Mar 28 '17 at 18:15
  • \$\begingroup\$ I found some things to golf, taking this down by 25% to 218 bytes. Not tested, but definitely worth a look. \$\endgroup\$ – Titus Mar 29 '17 at 16:16
  • 2
    \$\begingroup\$ a flaw in one of my golfings and six more bytes golfed: updated golfing list. \$\endgroup\$ – Titus Mar 29 '17 at 17:42
1
\$\begingroup\$

JavaScript, 242 236 235 231 220 bytes

a=>{n=a.length;m=x=y=p=0;a.map(g=>m=(w=g.length)<m?m:w);q=1,o="";while((t=a[y][x]||" ")!=";")o+=t,h=q,q=[q,1,0,p,-q][(s=">v\\| <^/_#".indexOf(t)+1)%5]*(r=s>5?-1:1),p=[p,0,1,h,p][s%5]*r,x=(x+q+m)%m,y=(y+p+n)%n;return o+t}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ you can save 13 char if you take in the string as an array. The specs were changed. \$\endgroup\$ – Not that Charles Apr 4 '17 at 22:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.