text:
De-Snakify a String
A regular string looks like this:
Hello,IAmAStringSnake!

And a string snake looks something like this:
Hel
  l      rin
  o,IAmASt g
           S
       !ekan

Your Task
String snakes are dangerous, so you must make a program that takes a string snake as input and outputs it as a regular string.
Specifications

Input can be a multiline string or an array of strings.
Each line of the input will be padded with spaces to form a rectangular grid.
Characters in the snake can only connect to adjacent characters above, below, left or right of them (just like in the game Snake). They cannot go diagonal.
The snake characters will never be adjacent to another part of the snake, only the connected characters.
The first character of the string is the end character with the shortest Manhattan distance from the top-left corner of the input grid (i.e. the minimum number of moves it would take for a snake to go directly from the end character to the top-left corner). Both ends will never have the same distance.
The string can contain any ASCII character between code points 33 and 126 inclusive (no spaces or newlines).
The string will be between 2 and 100 characters long.
Shortest code in bytes wins.

Test Cases
(Input grid, followed by the output string)
Hel
  l      rin
  o,IAmASt g
           S
       !ekan

Hello,IAmAStringSnake!

----------

Python

Python

----------

P  ngPu  Code
r  i  z  d  G
o  m  z  n  o
gram  lesA  lf

ProgrammingPuzzlesAndCodeGolf

----------

   ~ zyx tsr XWVUTSR
   }|{ wvu q Y     Q
!          p Z `ab P
"#$ 6789:; o [ _ c O
  % 5    < n \]^ d N
('& 432  = m     e M
)     1  > lkjihgf L
*+,-./0  ?         K
         @ABCDEFGHIJ

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

----------

  tSyrep
  r    p
  in Sli
   g    Sile
   Snakes  n
Ser      ylt
a eh   ilS
fe w   t
   emo h
     Sre

SlipperyStringSnakesSilentlySlitherSomewhereSafe

Fun Fact: According to the linked Wikipedia article, Manhattan distance is also known as snake distance!

Would an input like http://hastebin.com/asugoropin.vbs be correct ?

@FliiFe No, parts of the snake cannot be next to each other because it's not always possible to tell where the snake is going when this happens (and it would make the challenge a lot harder). I added a line to the spec to explain this.

Can the input be a two-dimensional array (i.e each character as an element) ?

@FliiFe Sure. Anything that works as long as it's in a "grid"-type format.

Surely this puzzle needs an answer in python?

What happens when both the start AND the end have the same manhattan distance?

@LuisMasuelli "Both ends will never have the same distance."

That last puzzle looks like Texas to me

@abligh It's a different species, in fact.

The premise reminds me of HPC channel: “It is EKS-tremely dein-gerous and may UTT-ack at any time, so we must DIEL wiz it!”

APL, 55 bytes
{⍵[1↓(⊂0 0){1<⍴⍵:⍺,∆[⊃⍋+/¨|⍺-∆]∇∆←⍵~⍺⋄⍺}(,⍵≠' ')/,⍳⍴⍵]}

This function takes a character matrix with the string snake in it.
Example:
      s1 s2 s3
┌────────────┬──────────────┬────────────────────┐
│Hel         │P  ngPu  Code │   ~ zyx tsr XWVUTSR│
│  l      rin│r  i  z  d  G │   }|{ wvu q Y     Q│
│  o,IAmAst g│o  m  z  n  o │!          p Z `ab P│
│           S│gram  lesA  lf│"#$ 6789;: o [ _ c O│
│       !ekan│              │  % 5    < n \]^ d N│
│            │              │('& 432  = m     e M│
│            │              │)     1  > lkjighf L│
│            │              │*+,-./0  ?         K│
│            │              │         @ABCDEFGHIJ│
└────────────┴──────────────┴────────────────────┘
      ↑ {⍵[1↓(⊂0 0){1<⍴⍵:⍺,∆[⊃⍋+/¨|⍺-∆]∇∆←⍵~⍺⋄⍺}(,⍵≠' ')/,⍳⍴⍵]} ¨ s1 s2 s3
Hello,IAmAstringSnake!
ProgrammingPuzzlesAndCodeGolf
!"#$%&'()*+,-./0123456789;:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefhgijklmnopqrstuvwxyz{|}~

Explanation:

(,⍵≠' ')/,⍳⍴⍵: get the coordinates of all non-spaces
(⊂0 0): begin at (0,0) (which is an invalid coordinate)
{...}: follow the snake, given position and snake:

1<⍴⍵:: if there is more than 1 element left:

∆←⍵~⍺: remove the current position from the snake and store it in ∆.
+/¨|⍺-∆: find the distance between the current position and each point in the rest of the snake
∆[⊃⍋...]`: get the closest point on the snake
∇: run the function again, with the closest point as the new current point and the shortened snake as the new snake.
⍺,: add the current position to the result of that

⋄⍺: otherwise, just return the current position

1↓: drop the first item from the result (which is the (0,0) position)
⍵[...]: get those elements from ⍵, in that order

fails at the last test: SlipperyStr..

JavaScript (ES6) + SnakeEx, 176 bytes
a=b=>snakeEx.run("s{A}:<+>([^ ]<P>)+",b).reduce((c,d)=>(e=c.marks.length-d.marks.length)>0?c:e?d:c.x+c.y>d.x+d.y?d:c).marks.reduce((c,d,e,f)=>e%2?c+b.split`\n`[d][f[e-1]]:c,"")

Remember SnakeEx? Good, because neither do I! Golfing suggestions welcome.

MATL, 80 bytes
Thanks to @LevelRiverSt for a correction
32>2#fJ*+X:4Mt1Y6Z+l=*2#fJ*+ttXjwYj+K#X<)wt!"tbb6#Yk2#)yw]xxvtXjwYjqGZy1)*+Gw)1e

Input is as a 2D array of char, with rows separated by ;. The test cases in this format are
['Hel         ';'  l      rin';'  o,IAmASt g';'           S';'       !ekan']
['Python']
['P  ngPu  Code ';'r  i  z  d  G ';'o  m  z  n  o ';'gram  lesA  lf']
['   ~ zyx tsr XWVUTSR';'   }|{ wvu q Y     Q';'!          p Z `ab P';'"#$ 6789:; o [ _ c O';'  % 5    < n \]^ d N';'(''& 432  = m     e M';')     1  > lkjihgf L';'*+,-./0  ?         K';'         @ABCDEFGHIJ']
['  tSyrep    ';'  r    p    ';'  in Sli    ';'   g    Sile';'   Snakes  n';'Ser      ylt';'a eh   ilS  ';'fe w   t    ';'   emo h    ';'     Sre    ']

Try it online!
Explanation
The coordinates of each nonspace character is represented by a complex number. For each current character, the next is obtained as that which is closest (minimum absolute difference of their complex coordinates).
To determine the initial char, the two endpoints need to be found. This is done as follows. An endpoint is a nonspace char that has exactly one nonspace neighbour. The number of neighbours is obtained by 2D convolution with a suitable mask. The initial point is the endpoint whose complex coordinate has the least sum of real and imaginary parts; i.e. is closest in Manhattan distance to the complex number 0, or equivalently to 1+1j, which is the complex coordinate of the upper left corner.
32>      % Take input as 2D char array. Compute 2D array with true for nonspace,
         % false for space
2#f      % Arrays of row and column indices of nonspaces
J*+      % Convert to complex array. Real part is row, imaginary part is column
X:       % Convert to column array
4Mt      % Push arrays of zeros and ones again. Duplicate
1Y6      % Push array [0 1 0; 1 0 1; 0 1 0]. Used as convolution mask to detect
         % neighbours that are nonspace
Z+       % 2D convolution with same size as the input
1=       % True for chars that have only one neighbour (endpoints)
*        % Multiply (logical and): we want nonspaces that are endpoints
2#fJ*+   % Find complex coordinates (as before)
ttXjwYj  % Duplicate. Take real and imaginary parts
+        % Add: gives Manhattan distance to (0,0)
K#X<     % Arg min. Entry with minimum absolute value has least Manhattan
         % distance to (0,0), and thus to (1,1) (top left corner)
)        % Apply as an index, to yield complex coordinate of initial endpoint
wt!      % Swap, duplicate, transpose.
         % The stack contains, bottom to top: complex coordinates of initial
         % endpoint, column array with all complex coordinates, row array of all
         % coordinates. The latter is used (and consumed) by the next "for"
         % statement to generate that many iterations
"        % For loop. Number of iterations is number of nonspaces
  tbb    %   Duplicate, bubble up twice (rearrange is stack)
  6#Yk   %   Find which of the remaining points is closest to current point. This
         %   is the next char in the string
  2#)    %   Remove the point with that index from the array of complex
         %   coordinates. Push that point and the rest of the array
  yw     %   Duplicate extracted point, swap
]        % End for
xx       % Delete top two elements of the stack
v        % Concatenate all stack contents into a column array. This array
         % contains the complex coordinates of chars sorted to form the string
tXjwYj   % Extract real part and imaginary part
GZy1)    % Number of rows of input. Needed to convert to linear index
*+       % Convert rows and columns to linear index
Gw       % Push input below that
)        % Index to get the original chars with the computed order
1e       % Force the result to be a row array (string). Implicitly display

I shall assume an explanation is forthcoming?

@Matt Sure... later in the day :-)

Explanation added @Matt

The initial point is the endpoint whose complex coordinate has the least absolute value Careful: Euclidean distance != Manhattan distance. for example the point 7+7j has Euclidean distance 9.8994 and Manhattan distance 14. 10j is further by Euclidean distance but considerably closer by Manhattan distance. Other than that, great concept!

@LevelRiverSt Thank you! Corrected

C  198   190   179   180  181 bytes
Edit: Used the tip by user81655 and removed the parenthesis in the ternary operator, thanks! I also changed the cumbersome (S&1) test for evenness for the more appropriate (and shorter!) S%2.
Edit2: Using the *a addressing style heavily, made me blind to the obvious optimizations in the definition of S, i.e., replacing *(a+m) by a[m] etc. I then replaced S itself by T, which essentially does half of what S does. The code also now takes advantage of the return value of putchar.
Edit3: Fixed bug that has been around from the beginning, the Manhattan-search stopping criteria a < b+m is correct only if a has already been decremented. This adds 2 bytes, but one is regained by making the definition of m global.
Edit4: My golfing has passed the minimum and is going the wrong way now. Another bug fix related to the Manhattan-search. I originally had in-bound checks in place and without those the search continues for large input arrays (somewhere round 50x50) beyond the array b. Hence that array has to be expanded to at least twice the previous size, which adds one more byte.
#define T(x)+x*((a[x]>32)-(a[-x]>32))
m=103;main(){char b[m<<8],*e=b,*a=e+m;while(gets(e+=m));for(e=a;(T(1)T(m))%2**a<33;a=a<b+m?e+=m:a)a-=m-1;for(;*a;a+=T(1)T(m))*a-=putchar(*a);}

Ungolfed and explained:
/* T(1)T(m) (formerly S) is used in two ways (we implicitly assume that each cell has
   one or two neighbors to begin with):
   1. (in the first for-loop) T(1)T(m) returns an odd (even) number if cell a has one (two)
      neighbors with ASCII value > 32. For this to work m must be odd.
   2. (in the second for-loop) at this stage each cell a in the array at which T(1)T(m) is
      evaluated has at most one neighboring cell with ASCII value > 32. T(1)T(m) returns the
      offset in memory to reach this cell from a or 0 if there is no such cell.
      Putting the + in front of x here saves one byte (one + here replaces two
      + in the main part)

#define T(x)+x*((a[x]>32)-(a[-x]>32))

  /* A snake of length 100 together with the newlines (replaced by 0:s in memory) fits
     an array of size 100x101, but to avoid having to perform out-of-bounds checks we
     want to have an empty line above and the array width amount of empty lines below
     the input array. Hence an array of size 202x101 would suffice. However, we save
     a (few) bytes if we express the array size as m<<8, and since m must be odd
     (see 1. above), we put m = 103. Here b and e point to the beginning of the (now)
     256x103 array and a points to the beginning of the input array therein */

m=103;
main()
{

  char b[m<<8],*e=b,*a=e+m;

  /* This reads the input array into the 256x103 array */

  while(gets(e+=m));

  /* Here we traverse the cells in the input array one
     constant-Manhattan-distance-from-top-left diagonal at a time starting at the top-left
     singleton. Each diagonal is traversed from bottom-left to top-right since the starting point
     (memory location e) is easily obtained by moving one line downwards for each diagonal
     (+m) and the stopping point is found by comparing the present location a to the input array
     starting position (b+m). The traversal is continued as long as the cell has either
     an ASCII value < 33 or it has two neighbors with ASCII value > 32 each (T(1)T(m)
     is even so that (T(1)T(m))%2=0).
     Note that the pointer e will for wide input arrays stray way outside (below) the
     input array itself, so that for a 100 cell wide (the maximum width) input array
     with only two occupied cells in the bottom-right corner, the starting cell
     will be discovered 98 lines below the bottom line of the input array.
     Note also that in these cases the traversal of the diagonals will pass through the
     right-hand side of the 103-wide array and enter on the left-hand side. This, however,
     is not a problem since the cells that the traversal then passes have a lower
     Manhattan distance and have thereby already been analyzed and found not to contain
     the starting cell. */

  for(e=a;(T(1)T(m))%2**a<33;a=a<b+m?e+=m:a)a-=m-1;

  /* We traverse the snake and output each character as we find them, beginning at the
     previously found starting point. Here we utilize the function T(1)T(m), which
     gives the offset to the next cell in the snake (or 0 if none), provided that
     the current cell has at most one neighbor. This is automatically true for the
     first cell in the snake, and to ensure it for the rest of the cells we put the
     ASCII value of the current cell to 0 (*a-=putchar(*a)), where we use the fact
     that putchar returns its argument. The value 0 is convenient, since it makes the
     stopping condition (offset = 0, we stay in place) easy to test for (*a == 0). */

  for(;*a;a+=T(1)T(m))
    *a-=putchar(*a);
}

This answer is great.

+1 This is great. I would like to add an explaination to my answer showing where I waisted bytes compared to your solution, is that OK?

mIllIbyte - feel free to add the comments, that's the road towards new ideas.

user81655 - thanks for the tip, it shaved off 6 bytes. In fact, I tried that yesterday as well as using S%2 instead of (S&1), which shaved off another 2 bytes, for the evenness test, but for some reason (my code was buggy somewhere else) neither worked appropriately then. Now, however, all seems ok.

Very nice. Save some more with a[1], a[-m] etc, and making m global - m=103;main().

Hi and thanks @ugoren, I implemented the a[1] etc. stuff before reading this comment, but the global m variable idea helped save one byte of two which were lost to a bug fix in the latest revision.

C, 272 bytes
#define E j+(p/2*i+1)*(p%2*2-1)
#define X(Y) a[Y]&&a[Y]-32
char A[999],*a=A+99;j,p,t;i;main(c){for(;gets(++j+a);j+=i)i=strlen(a+j);for(c=j;j--;){for(t=p=4;p--;)t-=X(E);t==3&&X(j)?c=c%i+c/i<j%i+j/i?c:j:0;}for(j=c;c;){putchar(a[j]),a[j]=0;for(c=0,p=4;!c*p--;)X(E)?c=j=E:0;}}

Look at @Zunga's source. Now look at mine. Want to know how I got the extra 91-bytes?
Ungolfed:
#define E j+(p/2*i+1)*(p%2*2-1)
#define X(Y) a[Y]&&a[Y]-32  //can be more concise, see @Zunga's
  //and then doesn't need the define
char A[999],*a=A+99;j,p,t;i;
main(c){for(;gets(++j+a);j+=i)
i=strlen(a+j); //we don't need to know the length of a line
  //in @Zunga's solution, lines are spaced a constant distance apart
for(c=j;j--;){
for(t=p=4;p--;)t-=X(E);  //a ton of bytes can be saved with determining
  //the neighbors, see @Zunga's source
t==3&&X(j)?
c=c%i+c/i<j%i+j/i?c:j:0;}  //we search for ends of the snake,
  //and compute the Manhattan distance
for(j=c;c;){putchar(a[j]),a[j]=0;
for(c=0,p=4;!c*p--;)  //determining the neighbors again
X(E)?c=j=E:0;}}

Python (2 and 3), 640 624 604 583 575 561 546 538 bytes
I'm still a golfing n00b so this is a bit large.
Edit: Thanks to @porglezomp for the suggestions! I didn't remove all the 'and' operators as that would break Python 3.
Edit2: Thanks to @Aleksi Torhamo for the comment about isspace(). The resulting reduction compensates for the bugfix I put in. Also thanks to anonymous for the syntax highlighting!
Edit3: Thanks to @mbomb007 for a few additional bytes.
import sys;s=sys.stdin.read().split('\n');m={};q=[];o=len;j=o(s);r=range;g='!'
for y in r(j):
 v=s[y];f=o(v);d=y+1
 for x in r(f):
  n=[];a=n.append;U=s[y-1]
  if v[x]>=g:j>=y>0==(U[x]<g)<=x<o(U)and a((x,y-1));j>y>=0==(v[x-1]<g)<x<=f and a((x-1,y));j>y>-1<x+1<f>(v[x+1]<g)<1and a((x+1,y));j>d>-1<x<o(s[d])>(s[d][x]<g)<1and a((x,d));m[x,y]=[v[x],n];o(n)-1or q.append((x,y))
t=min(q,key=sum);w=sys.stdout.write;w(m[t][0]);c=m[t][1][0]
while o(m[c][1])>1:
 b=m[c][1];w(m[c][0])
 for k in r(o(b)):
  if b[k]!=t:t=c;c=b[k];break
print(m[c][0])

And here's my pre-golf version
import sys

lines = sys.stdin.read().split('\n')
startend = []
mydict = {}
for y in range( 0, len(lines)):
  for x in range( 0, len(lines[y])):
    if not lines[y][x].isspace():
      neighbors = []
      if x>=0 and x<len(lines[y-1]) and y-1>=0 and y-1<len(lines):
        if not lines[y-1][x].isspace():
          neighbors.append( (x,y-1) )
      if x-1>=0 and x-1<len(lines[y]) and y>=0 and y<len(lines):
        if not lines[y][x-1].isspace():
          neighbors.append( (x-1,y) )
      if x+1>=0 and x+1<len(lines[y]) and y>=0 and y<len(lines):
        if not lines[y][x+1].isspace():
          neighbors.append( (x+1,y) )
      if x>=0 and x<len(lines[y+1]) and y+1>=0 and y+1<len(lines):
        if not lines[y+1][x].isspace():
          neighbors.append( (x,y+1) )
      mydict[(x,y)] = [ lines[y][x], neighbors ]

      if len( neighbors ) == 1:
        startend.append( (x,y) )

startend.sort( key=lambda x : x[0]*x[0] + x[1]*x[1] )

last = startend[0]
sys.stdout.write( mydict[ last ][0] )
current = mydict[last][1][0]
while len( mydict[current][1] ) > 1:
  sys.stdout.write( mydict[current][0] )
  for k in range( 0, len( mydict[current][1] ) ):
    if mydict[current][1][k] != last:
      last = current
      current = mydict[current][1][k]
      break

print(mydict[current][0])

I saved 12 bytes by introducing S=lambda s:s.isspace() and then doing S(s) instead of s.isspace().

I think you can also change all of your and  to <, since f() < g() < h() is the same as g = g(); f() < g and g < h() in terms of side effects (comparison chains short circuit), and you're ignoring the result of the comparisons anyway.

m[(x,y)]= is the same as the shorter m[x,y]=

@porglezomp: it's even shorter to say S=str.isspace

Removing S and instead using <'!' in every occurrence can be the same length, possibly opening an opportunity to save more. Changing if 1-S(v[x]): to if(v[x]<'!')<1:, for example. And maybe you could remove some parentheses in the later comparisons by doing it that way.

So this is the same length if(v[x]<'!')<1:j>=y>0==(U[x]<'!')<=x<o(U)and a((x,y-1));j>y>=0==(v[x-1]<'!')<x<=f and a((x-1,y));j>y>-1<x+1<f>(v[x+1]<'!')<1and a((x+1,y));j>y+1>-1<x<o(T)>(T[x]<'!')<1and a((x,y+1));m[x,y]=[v[x],n];o(n)-1or q.append((x,y)) if you removed S.

JavaScript (ES6), 195
See explanation inside the test snippet
s=>[...s].map((c,i)=>{if(c>' '&([n=-1,1,o=-~s.search('\n'),-o].map(d=>n+=s[i+d]>' '&&!!(e=d)),n<1)&m>(w=i/o+i%o|0))for(m=w,r=c,p=i+e;r+=s[i=p],[e,o/e,-o/e].some(d=>s[p=i+(e=d)]>' '););},m=1/0)&&r

Test

f=s=>[...s].map((c,i)=>{if(c>' '&([n=-1,1,o=-~s.search('\n'),-o].map(d=>n+=s[i+d]>' '&&!!(e=d)),n<1)&m>(w=i/o+i%o|0))for(m=w,r=c,p=i+e;r+=s[i=p],[e,o/e,-o/e].some(d=>s[p=i+(e=d)]>' '););},m=1/0)&&r

// Less golfed

u=s=>(
  o = -~s.search('\n'), // offset between lines
  m = 1/0, // current min manhattan distance, init at infinity
  // scan input looking for the 2 ends of the string
  [...s].map((c,i)=>{ // for each char c at position i
     if(c > ' ' // check if part of the string
        & ( [-1,1,o,-o] // scan in 4 directions and count neighbors
             .map(d=> n+=s[i+d]>' '&&!!(e=d), n=0), // remember direction in e
          n < 2) // if at end of string will have exactly 1 neighbor
        & (w = i/o + i%o |0) < m) // manhattan distance in w, must be less than current min
       // found one of the ends, follow the path and build the string in r
       for(m = w, r = c, p = i+e;
           r += s[i=p],
           [e,o/e,-o/e] // check 3 directions, avoiding to go back
           .some(d=>s[p=i+(e=d)]>' '); // save candidate position and direction in p and e
          ); // empty for body, all the work is inside the condition
  }),
  r
)

console.log=x=>O.textContent+=x+'\n'

;[`Hel
  l      rin
  o,IAmASt g
           S
       !ekan`,
 `   ~ zyx tsr XWVUTSR
   }|{ wvu q Y     Q
!          p Z \`ab P
"#$ 6789:; o [ _ c O
  % 5    < n \\]^ d N
('& 432  = m     e M
)     1  > lkjihgf L
*+,-./0  ?         K
         @ABCDEFGHIJ`].forEach(t=>{
  console.log(t+'\n\n'+f(t)+'\n')
  })
<pre id=O></pre>

Are the semicolons in ););} needed?

@CeesTimmerman yes. The first is inside the for header where 2 colons are needed. The second is the delimeter for the for body

APL (Dyalog Unicode), 59 bytes
{⍵[i][{⍵∪⍸∨⌿g[⍵;]}⍣≡,j⊃⍨⊃⍋+/↑i[j←⍸≠/g←1=+/|↑∘.-⍨i←⍸' '≠⍵]]}

Try it online!

Lua, 562 535 529 513 507 504 466 458 Bytes
By far my most massive golf at the moment, I think I can still cut off 100 bytes, which I'll work toward, but posting it as an answer as it already took some time :). I was right, I've cutted down more than 100 bytes! I don't think there's lot of room for improvement.
this function have to be called with a 2D array containing one character per cell.
Saved 40 bytes while working with @KennyLau, thanks to him!
Woohoo! Under 500!
function f(m)t=2u=1i=1j=1s=" "::a::if s~=m[i][j]and(i<#m and m[i+1][j]~=s)~=(j<#m[i]and m[i][j+1]~=s)~=(i>1 and m[i-1][j]~=s)~=(j>1 and m[i][j-1]~=s)then goto b end
i,t=i%t+1,#m>t and t==i and t+1or t j=j>1 and j-1or u u=u<#m[1]and j==1 and u+1or u goto a::b::io.write(m[i][j])m[i][j]=s
i,j=i<#m and s~=m[i+1][j]and i+1or i>1 and s~=m[i-1][j]and i-1or i,j<#m[i]and s~=m[i][j+1]and j+1or j>1 and s~=m[i][j-1]and j-1or j
if s==m[i][j]then return end goto b end

Ungolfed
Explanations will come once I'm done golfing this, for the moment, i'll lend you a readable version of this source code :D Here comes the explanations!
Edit: not updated with the latest modification, still golfing before updating. Same goes for the explanations
function f(m)                    -- declare the function f which takes a matrix of characters
  t=2                            -- initialise the treshold for i
                                 -- when looking for the first end of the snake
  u=1                            -- same thing for j
  i,j=1,1                        -- initialise i and j,our position in the matrix
  s=" "                          -- shorthand for a space
  ::a::                          -- label a, start of an infinite loop
    if m[i][j]~=s                -- check if the current character isn't a space
      and(i<#m                   -- and weither it is surrounded by exactly
          and m[i+1][j]~=s)      -- 3 spaces or not
      ~=(j<#m[i]
          and m[i][j+1]~=s)      -- (more explanations below)
      ~=(i>1
          and m[i-1][j]~=s)
      ~=(j>1
          and m[i][j-1]~=s)
      then goto b end            -- if it is, go to the label b, we found the head
    i,t=                         -- at the same time
      i%t+1,                     -- increment i
      #m>t and t==i and t+1or t  -- if we checked all chars in the current range, t++
    j=j>1 and j-1or u            -- decrement j
    u=u>#m[1]and j==1 and u+1or u-- if we checked all chars in the current range, u++
  goto a                         -- loop back to label a

  ::b::                          -- label b, start of infinite loop
  io.write(m[i][j])                    -- output the current char
    m[i][j]=s                    -- and set it to a space
    i,j=i<#m                     -- change i and j to find the next character in the snake
          and m[i+1][j]~=s       -- this nested ternary is also explained below
            and i+1              -- as it takes a lot of lines in comment ^^'
          or i>1
            and m[i-1][j]~=s
            and i-1
          or i,
       j<#m[i]
         and m[i][j+1]~=s
           and j+1
         or j>1
           and m[i][j-1]~=s
           and j-1
         or j
    if m[i][j]==s                -- if the new char is a space
    then                         -- it means we finished
      return                  -- exit properly to avoid infinite
    end                          -- printing of spaces
  goto b                         -- else, loop back to label b
end

So here comes some detailed explanations about how this program works.
First of all, let's consider the loop labeled a, it allows us to find the closest end to the top-left corner. It will loop forever if there's no end, but that's not a problem :D.
On a 4x4 grid, it here are the snake distances(left), and the order they are looked at (right)
1  2  3  4    |     1  2  4  7
2  3  4  5    |     3  5  8 11
3  4  5  6    |     6  9 12 14
4  5  6  7    |    10 13 15 16

For each of this character, to be the end, it have to check two conditions:
  -  Not being a space
  -  Being surrounded by exactly 3 spaces (or exactly 1 non-space)
These conditions are checked the following piece of code
r=m[i][j]~=s
    and(i<#m and m[i+1][j]~=s)
    ==not(j<#m[i] and m[i][j+1]~=s)
    ==not(i-1>0 and m[i-1][j]~=s)
    ==not(j-1>0 and m[i][j-1]~=s)
    and m[i][j]
    or r
  -- special note: "==not" is used as an equivalent to xor
  -- as Lua doesn't know what is a xor...

Checking if the char isn't a space is achieved by the expression m[i][j]~=s.
Checking if w're surrounded by only 1 non-space is achived by xor-ing the above conditions for our surrounding, this could be written as
m[i+1][j]~=" " ⊕ m[i][j+1]~=" " ⊕ m[i-1][j]~=" " ⊕ m[i][j-1]~=" "

And finally, if all the above is evaluated to true, the ternary will return what's in the last and -> m[i][j]. Else , we let r unset :)
Now that we have the head of the snake, let's get all the way to the other end! Iterating the snake is mainly achieved by the following nested ternaries:
i,j=i<#m and m[i+1][j]~=s and i+1or i-1>0 and m[i-1][j]~=s and i-1or i,
    j<#m[i]and m[i][j+1]~=s and j+1or j-1>0 and m[i][j-1]~=s and j-1or j

We re-set i and j at the same time to avoid needing dummies to store the old values They both have the exact same structure, and use simple conditions, so I'll present them in the form of nested if, it should allow you to read them more easily. :)
i=i<#m and m[i+1][j]~=s and i+1or i-1>0 and m[i-1][j]~=s and i-1or i

Can be translated to:
if(i<#m)
then
  if(m[i+1][j]~=" ")
  then
    i=i+1
  end
elseif(i-1>0)
then
  if(m[i-1][j]~=" ")
  then
    i=i-1
  end
end

Test it!
Here's the code I use to run this, you can test it online by copy-pasting it.
function f(m)t=2u=1i=1j=1s=" "::a::if s~=m[i][j]and(i<#m and m[i+1][j]~=s)~=(j<#m[i]and m[i][j+1]~=s)~=(i>1 and m[i-1][j]~=s)~=(j>1 and m[i][j-1]~=s)then goto b end
i,t=i%t+1,#m>t and t==i and t+1or t j=j>1 and j-1or u u=u<#m[1]and j==1 and u+1or u goto a::b::io.write(m[i][j])m[i][j]=s
i,j=i<#m and s~=m[i+1][j]and i+1or i>1 and s~=m[i-1][j]and i-1or i,j<#m[i]and s~=m[i][j+1]and j+1or j>1 and s~=m[i][j-1]and j-1or j
if s==m[i][j]then return end goto b end

test1={}
s1={
"  tSyrep    ",
"  r    p    ",
"  in Sli    ",
"   g    Sile",
"   Snakes  n",
"Ser      ylt",
"a eh   ilS  ",
"fe w   t    ",
"   emo h    ",
"     Sre    ",
     }
for i=1,#s1
do
  test1[i]={}
  s1[i]:gsub(".",function(c)test1[i][#test1[i]+1]=c end)
end
f(test1)

A have a soft spot for longer answers that have little to now choice because of the language choice.

@Matt thanks a lot for the support! actually, i'm still finding ways to golf this down, but it's getting harder and harder!

Lua, 267 bytes
Lua 5.3 is required.
e=" "w=#arg[1]+1i=1/0q=0s=table.concat(arg,e)s=e:rep(#s)..s
m,n=i,{}for p in s:gmatch"()%g"do u=-1
for _,d in ipairs{-1,1,-w,w}do u=u+(s:find("^%S",d+p)or 0)end
n[p]=u+1m=math.min(m,p*i^(u//#s)+(p%w*w+p)*#s)end
p=m%#s repeat q,p=p,n[p]-q io.write(s:sub(q,q))until p<1

Usage:
$ lua desnakify.lua \
>    "  tSyrep    " \
>    "  r    p    " \
>    "  in Sli    " \
>    "   g    Sile" \
>    "   Snakes  n" \
>    "Ser      ylt" \
>    "a eh   ilS  " \
>    "fe w   t    " \
>    "   emo h    " \
>    "     Sre    "
SlipperyStringSnakesSilentlySlitherSomewhereSafe

Python 3, 245 243 241 236 bytes
s is the input string, n is the output printed to stdout:
f=s.find
w,l=f('\n')+1,len(s)
t=1,w,-1,-w
y=z=f(s.strip()[0]);n=s[y];v={y}
for i in range(l*l):
 i%=l;c=s[i]
 if c>' 'and i not in v:
  if i-y in t:y=i;n=c+n;v|={i}
  elif i-z in t:z=i;n+=c;v|={i}
if y%w+y//w>z%w+z//w:n=n[::-1]
print(n)

Edit: Thanks to @Cees Timmerman for saving 5 bytes!

c>' 'and and print n in Python 2.

Can't you do if instead of elif?

@Qwerp-Derp unfortunately not, I have tried it before, but it prints, for example "!ekanSgnirtSAmAI,olleHello,IAmAStringSnake!" and "SlipperyStSyreppilS".

What's the input format?

@Qwerp-Derp s variable is a multiline string; the last character of the string must be a newline (this is necessary to pass the Python test case)

Why does this only output gnirtSyreppilS for the "Slippery String Snakes" test case?

@Qwerp-Derp for me it outputs SlipperyStSyreppilS, it's because if we have if instead of elif then both the y and z variables always contain the same index, so the snake is traversed in only one way, stopping on the closer end; also, each char is added to both ends so we end up with a symmetric string

@pgks Yeah, but this is for the "elif". Does it make a difference in output if I use Python 2?

Python, 537
My initial solution:
from itertools import chain, product, ifilter
from operator import add
moves = ((1,0),(0,1),(-1,0),(0,-1))
h = dict(ifilter(lambda (p,v):not v.isspace(),chain(*map(lambda (i,r):map(lambda (j,c):((i,j),c),enumerate(r)),enumerate(s)))))
n = defaultdict(list)
for m,p in product(moves, h):
    np = tuple(map(add,m,p))
    if np in h:
        n[p].append(np)
def pr(nx):
    return(lambda l:(h[l[0]], h.pop(l[0]))[0] + pr(l[0]) if l else '')([x for x in n[nx] if x in h])
(lambda y: h[y]+ pr(y))(next(x for x in n if len(n[x])==1))

Compacted a bit, but left it as a method:
from itertools import chain, product
from operator import add
def unsnake(s):
    (h,n) = (dict(filter(lambda (p,v):not v.isspace(),chain(*map(lambda (i,r):map(lambda (j,c):((i,j),c),enumerate(r)),enumerate(s))))),defaultdict(list))
    for m,p in product(((1,0),(0,1),(-1,0),(0,-1)), h):(lambda np: n[p].append(np) if np in h else 0)(tuple(map(add,m,p)))
    def pr(nx):return(lambda l:(h[l[0]], h.pop(l[0]))[0] + pr(l[0]) if l else '')([x for x in n[nx] if x in h])
    return(lambda y: h[y]+ pr(y))(next(x for x in n if len(n[x])==1))

Java 7, 927 924 923 bytes
import java.util.*;int l,k;char[][]z;Set p=new HashSet();String c(String[]a){int x=0,y=0,n,t,u,v,w=t=u=v=-1;l=a.length;k=a[0].length();z=new char[l][k];for(String s:a){for(char c:s.toCharArray())z[x][y++]=c;}x++;y=0;}for(x=0;x<l;x++)for(y=0;y<k;y++){n=0;if(z[x][y]>32){if(x<1|(x>0&&z[x-1][y]<33))n++;if(y<1|(y>0&&z[x][y-1]<33))n++;if(x>l-2|(x<l-1&&z[x+1][y]<33))n++;if(y>k-2|(y<k-1&&z[x][y+1]<33))n++;}if(n>2&t<0){t=x;u=y;}if(n>2&t>v){v=x;w=y;}}if(v+w>t+u){p(t,u);return n(""+z[t][u],t,u);}p(v,w);return n(""+z[v][w],v,w);}String n(String r,int x,int y){int a,b;if(x>0&&z[a=x-1][b=y]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}if(y>0&&z[a=x][b=y-1]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}if(x<l-1&&z[a=x+1][b=y]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}if(y<k-1&&z[a=x][b=y+1]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}return r;}boolean q(int x,int y){return!p.contains(x+","+y);}void p(int x,int y){p.add(x+","+y);}

Ok, that took a while.. In some programming languages it doesn't matter if your array x and y are outside the boundaries of a 2D-array, but with Java it'll throw ArrayIndexOutOfBoundsExceptions, so everything has to be checked..
I first determine the starting point, and then use a recursive method to build the string from there. In addition, I use a list to keep track of the coordinations I've already encountered, so it won't go into a loop back-forth-back-forth (resulting in a StackOverflowException).
This is probably the longest answer I've posted so far, but although some parts can be golfed, I don't think this challenge can be that much shorter in Java. Java just isn't suitable for following a path in a grid.. It was a fun challenge to figure out nonetheless. :)
Ungolfed & test cases:
Try it here.
import java.util.*;
class M{
  static int l,
             k;
  static char[][] z;
  static Set p = new HashSet();

  static String c(String[] a){
    int x=0,
        y=0,
        n,
        t,
        u,
        v,
        w = t = u = v = -1;
    l = a.length;
    k = a[0].length();
    z = new char[l][k];
    for(String s:a){
      for(char c:s.toCharArray()){
        z[x][y++] = c;
      }
      x++;
      y = 0;
    }
    for(x=0; x<l; x++){
      for(y=0; y<k; y++){
        n = 0;
        if(z[x][y] > 32){ // [x,y] is not a space
          if(x < 1 | (x > 0 && z[x-1][y] < 33)){
            n++;
          }
          if(y < 1 | (y > 0 && z[x][y-1] < 33)){
            n++;
          }
          if(x > l-2 | (x < l-1 && z[x+1][y] < 33)){
            n++;
          }
          if(y > k-2 | (y < k-1 && z[x][y+1] < 33)){
            n++;
          }
        }
        if(n > 2 & t < 0){
          t = x;
          u = y;
        }
        if(n > 2 & t > v){
          v = x;
          w = y;
        }
      }
    }
    if(v+w > t+u){
      p(t, u);
      return n(""+z[t][u], t, u);
    }
    p(v, w);
    return n(""+z[v][w], v, w);
  }

  static String n(String r, int x, int y){
    int a,b;
    if(x > 0 && z[a=x-1][b=y] > 32 & q(a,b)){
      p(a, b);
      return n(r+z[a][b], a, b);
    }
    if(y > 0 && z[a=x][b=y-1] > 32 & q(a,b)){
      p(a, b);
      return n(r+z[a][b], a, b);
    }
    if(x < l-1 && z[a=x+1][b=y] > 32 & q(a,b)){
      p(a, b);
      return n(r+z[a][b], a, b);
    }
    if(y < k-1 && z[a=x][b=y+1] > 32 & q(a, b)){
      p(a, b);
      return n(r+z[a][b], a, b);
    }
    return r;
  }

  static boolean q(int x, int y){
    return !p.contains(x+","+y);
  }

  static void p(int x, int y){
    p.add(x+","+y);
  }

  public static void main(String[] a){
    System.out.println(c(new String[]{ "Hel         ",
      "  l      rin",
      "  o,IAmASt g",
      "           S",
      "       !ekan" }));
    p = new HashSet();
    System.out.println(c(new String[]{ "Python" }));
    p = new HashSet();
    System.out.println(c(new String[]{ "P  ngPu  Code ",
      "r  i  z  d  G",
      "o  m  z  n  o",
      "gram  lesA  lf" }));
    p = new HashSet();
    System.out.println(c(new String[]{ "   ~ zyx tsr XWVUTSR",
      "   }|{ wvu q Y     Q",
      "!          p Z `ab P",
      "\"#$ 6789:; o [ _ c O",
      "  % 5    < n \\]^ d N",
      "('& 432  = m     e M",
      ")     1  > lkjihgf L",
      "*+,-./0  ?         K",
      "         @ABCDEFGHIJ" }));
    p = new HashSet();
    System.out.println(c(new String[]{ "  tSyrep    ",
      "  r    p   ",
      "  in Sli   ",
      "   g    Sile",
      "   Snakes  n",
      "Ser      ylt",
      "a eh   ilS ",
      "fe w   t   ",
      "   emo h   ",
      "     Sre    " }));
  }
}

Output:
Hello,IAmAStringSnake!
Python
ProgrammingPuzzlesAndCodeGolf
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
SlipperyStringSnakesSilentlySlitherSomewhereSafe

924 bytes, jesus christ... lol

@BasicallyAlanTuring Hehe. I simply made the challenge, code-golfed it, and then looked at the byte-count. Was indeed a lot higher than expected, but ah well, at least it's below 1k... If you see anything to improve let me know, and if you have an alternative approach with (a lot) less bytes feel free to make a separate post; I'd be interested to see it. PS: It's now 923 bytes. XD

No need to check everythig, just add some padding to your string. Probably using a single multiline string makes that easier. Have a look to my C# answer ported from javascript

C#, 310
(Edit: bug fix)
A function with a multiline string parameter, returning a string.
Including the requested using in the byte count.
This is a porting of my javascript answer.
using System.Linq;
string f(string s){int o=-~s.IndexOf('\n'),m=99;var r=new string(' ',o);(s=r+s+r).Select((c,i)=>{int n=2,e=0,p,w=i%o+i/o;if(c>' '&w<m&&new[]{-1,1,o,-o}.All(d=>(s[i+d]>' '?(e=d)*--n:n)>0))for(m=w,r=""+c+s[p=i+e];new[]{e,o/e,-o/e}.Any(d=>s[p+(e=d)]>' ');)r+=s[p+=e];return i;}).Max();return r;}

Test on ideone
With spaces
    string f(string s)
    {
        int o = -~s.IndexOf('\n');
        var r = new string(' ', o);
        var m = 99;
        (s = r + s + r).Select((c, i) =>
        {
            int n = 2, e = 0, p, w = i % o + i / o;
            if (c > ' ' & w < m & new[] { -1, 1, o, -o }.All(d => (s[i + d] > ' ' ? (e = d) * --n : n) > 0))
                for (m = w, r = "" + c + s[p = i + e];
                     new[] { e, o / e, -o / e }.Any(d => s[p + (e = d)] > ' ');
                     )
                   r += s[p += e];
            return i;
        }
        ).Max();
        return r;
    }

PHP, 199 184 182 bytes
may still have a little golfing potential
for($w=strpos($i=$argv[1],"
");;)for($y=++$n;$y--;)if($i[$p=$y*$w+$n-1]>" ")break 2;for($p-=$d=$w++;$d&&print$i[$p+=$e=$d];)foreach([-$w,-1,1,$w,0]as$d)if($d+$e&&" "<$i[$d+$p])break;

takes input as multiline string from command line, expects linux style linebreaks.
Run php -r '<code>' '<string>'; escape linebreaks.
breakdown
for(
    // find width
    $w=strpos($i=$argv[1],"\n")
    ;
    // find first character: initialize $p(osition)
    ;
)
    for($y=++$n             // increase distance
        ;$y--;)             // loop $y from (old)$n to 0
        if(" "<$i[$p=$y*$w+$n   // if character at $y*($width+1)+$x(=$d-$y) is no space
            -1                  // (adjust for the premature increment)
        ])
            break 2;                    // break loops

for(
    $p-=            // b) reverse the increment that follows in the pre-condition
    $d=             // a) initialize $d to anything!=0 to enable the first iteration
    $w++;           // c) increase $w for easier directions
    $d              // loop while direction is not 0 (cursor has moved)
    &&
    print$i[$p+=$e=$d]              // remember direction, move cursor, print character
    ;
)
    foreach([-$w,-1,1,$w,0]as$d)// loop through directions
        if($d+$e                    // if not opposite previous direction
            &&" "<$i[$d+$p]         // and character in that direction is not space
        )break;                     // break this loop

Python 2, 251 bytes
w=s.find('\n')+1;q=' ';p=q*w+'\n';s=list(p+s+p);d=-w,1,w,-1
def r(x):c=s[x];s[x]=q;v=[c+r(x+o)for o in d if s[x+o]>q];return v[0]if v else c
e=[x for x in range(len(s))if s[x]>q and sum([s[x+o]>q for o in d])<2]
print r(e[e[0]/w+e[0]%w>e[1]/w+e[1]%w])

Or, if you want leading newlines in your testcases, 257 bytes:
w=s.find('\n',1);q=' ';p=q*-~w+'\n';s=list(p+s[1:]+p);d=-w,1,w,-1
def r(x):c=s[x];s[x]=q;v=[c+r(x+o)for o in d if s[x+o]>q];return v[0]if v else c
e=[x for x in range(len(s))if s[x]>q and sum([s[x+o]>q for o in d])<2]
print r(e[e[0]/w+e[0]%w>e[1]/w+e[1]%w])

Passes all testcases.
s="""
  tSyrep
  r    p
  in Sli
   g    Sile
   Snakes  n
Ser      ylt
a eh   ilS
fe w   t
   emo h
     Sre
"""

Results in:
SlipperyStringSnakesSilentlySlitherSomewhereSafe

I think you can replace b.append(...) with b+=[...] and def n(x,y):return ... with n=lambda x,y:...

Create a variable for ' '.

and use ~-x instead of x-1, you won't have to use parentheses.

Japt -P, 106 bytes
K=U·ÌÊÄ ç iU ¬mx T=[-KJ1K]
ËÊ*Tm+E è@gX
[]V£YÃf@gXÃrQ@WpQ Tm+Q kW fZ Ì}V£[XYuK YzK]ÃkÈv ÉÃñx v rÈ+Y*K
W£gX

Try it online!
It's... um... an abomination.
Unpacked & How it works
K=UqR gJ l +1 ç iU q mx
  UqR gJ l +1            Split the input by newline, take last item's length +1
K=                       Assign to K
              ç iU       Generate a string of K spaces, and append to U
                   q mx  Split into chars, and trim whitespaces on each item
                         Implicit assign to U

T=[-KJ1K]  Assign an array [-K, -1, 1, K] to T (this represents 4-way movement)
           I could use implicit assignment, but then 4-argument function below is broken

UmDEF{Dl *Tm+E èXYZ{UgX
UmDEF{                   Map over the list of one- or zero-length strings...
      Dl *                 If the length is zero, return zero
          Tm+E             Add the index to each element of T
               èXYZ{UgX    Count truthy elements at these indices
                         The result is an array of 0(space/newline), 1(start/end), or 2(body)
                         Implicit assign to V

[]  Implicit assign to W

VmXYZ{Y} fXYZ{UgX} rQXYZ{WpQ Tm+Q kW fZ gJ }
VmXYZ{Y}                                      Map V into indices
         fXYZ{UgX}                            Filter the indices by truthiness of U's element
                   rQXYZ{                     Reduce on the indices... (Q=last item, Z=array)
                         WpQ                    Push Q to W
                             Tm+Q               Take 4-way movements from Q
                                  kW fZ gJ }    Exclude visited ones, take last one in Z

VmXYZ{[XYuK YzK]} kXYZ{Xv -1} ñx v rXYZ{X+Y*K  Starting point of reduce
VmXYZ{[XYuK YzK]}                              Convert elements of V to [elem, col, row]
                  kXYZ{Xv -1}                  Take the ones where elem(popped)=1
                              ñx v             Sort by row+col and take first one
                                   rXYZ{X+Y*K  Convert [row,col] back to the index

WmXYZ{UgX  Map indices back to chars

-P  Join with empty string

One notable point is that I used the operator precedence between assignment and comma operators in JS, in order to pack some lines and keep the shortcut @ (XYZ{) usable.


text:
Is the path correct?
Is the path correct ?
Given a string, your program must determine whether or not Alice can reach Bob, following the signs on the map. You must return a truthy or falsy value.
The input string will contain the following characters :

 (space) and \n. Only used for padding.
>, <, ^, v, are the "signs". They show the direction.
&. Ignore next char, whatever it is (including spaces and Bob)
A and B respectively Alice and Bob.

The map is a torus. If Alice reaches the end of a row, then she is teleported back to the beginning of that row. Same applies for columns.
Examples
Given those examples as input, your program must return a truthy value (each input is separated with a - line):
A>B
-----------------
<BA
-----------------
A       B
-----------------
BA
-----------------
Av  >B
 >  ^
-----------------
Av
 B
-----------------
A>v
  >B
-----------------
A>v>   v>B
 v< > &<^
 > ^
-----------------
A>v>   v
 v< >B&<
 > ^
-----------------
A&<B
-----------------
A&B<
-----------------
<A       &B

For the following, your program must output a falsy value or nothing :
AvB
-----------------
A&B
-----------------
A><B
-----------------
A>v
 ^<B

Path viewer
You can have a visual representation of the input here. Thanks to arnemart for this.
Some rules

The input may be padded with spaces to form a rectangle
Initially, Alice goes straight forward (from above, she goes to the right)
Your program should handle infinite loop cases (see Hint)
A is not always the first character, as you may have seen, however, you may write a program that handles only input with A being the first char, but 20 bytes will be added to your score.
A map (the input) is considered invalid in case there are other characters than those specified above. Your program won't have to handle them.
This is code-golf, so shortest code in bytes wins.

Hint
Your program will most likely be a loop, unless you find a more mathematical solution to this challenge. To handle infinite path, I recommend using a finite loop (e.g for) instead of a potentially infinite one (e.g while).
Therefore, the maximum iteration of the loop I can think of (I did not do any maths, any correction is welcome) is (length of input)*4

Closely related -- http://codegolf.stackexchange.com/q/57952/42963

Can the input be padded with spaces so that it forms a rectangle and each line is the same length?

@user81655 Yes it can

If only there was a way to replace a few chars then exec in ><>...

@mbomb007  Sorry :D

Also related.

Alice is a male? o_O

Can I take the input as a string array passed to the main method of a Java program?

@AlexL. Yes you can. I think someone corrected the he. But orignially, Alice was in fact John (which I replaced to match A and B, and also because Alice and Bob are well known)

@FliiFe Okay. Thanks. B will always be present, right?

@AlexL. Yes. You basically don't have do handle any unexpected input.

@AlexL. She was a male. I turned her to a female on my last edit. Just didn't press [s] well, I think.

C, 250 bytes
#define h x=(j+x-1+d%3)%j,i=(j+i+(d=='v')-(d==94))%j
char a[999],b[999];x,i,d=2,k,f;main(j){for(;gets(a+j*i);)j=strlen(a+j*i++);for(x=strchr(a,65)-a,i=x/j,x=x%j;!k*d;h)k|=b[f=j*i+x]&1<<d%5,b[f]|=1<<d%5,(f=a[f])&16?d=f:f&4?h:f&2?d=0:0;putchar(48+!k);}

This also requires that the input is padded with spaces.
Ungolfed:
#define h x=(j+x-1+d%3)%j,i=(j+i+(d=='v')-(d==94))%j
char a[999],b[999];x,i,d=2,k,f;
main(j){
 for(;gets(a+j*i);)j=strlen(a+j*i++); //read lines and determine line length
 for(x=strchr(a,65)-a,i=x/j,x=x%j;    //the current position is 'A'
 !k*d; //as long as we have not arrived at 'B'
       //and not travelled through the same cell and in the same direction twice
 h)    //advance one in the current direction
   k|=b[f=j*i+x]&1<<d%5,b[f]|=1<<d%5,  //if we have already travelled
                                       //through this cell in this direction
   (f=a[f])&16?d=f //change direction if this cell is one of <>^v
   :f&4?h          //if this cell is '&', advance one in the current direction
   :f&2?d=0:0;     //if we have reached 'B'
 putchar(48+!k);
}

JavaScript (ES6), 176 bytes
m=>[...m,q=~m.length,l=~m.search`
`||q,a=m.search`A`,p=d=r=1].map(_=>(a+=d,a-=d*((a-l+1)%l?m[a]?0:q/l:~l),c=m[a],p=="&"?0:d={">":1,"<":-1,"^":l,v:-l}[c=="B"?r=0:c]||d,p=c))&&!r

Explanation
Requires the input to be space-padded to form a rectangle (I hope this is OK).

var solution =

m=>[
    ...m,                           // iterate m.length times
    q=~m.length,                    // q = total length of m
    l=~m.search`\n`||q,             // l = line length
    a=m.search`A`,                  // a = index of Alice
    p=                              // p = previous character
    d=                              // d = direction offset
    r=1                             // r = result
  ].map(_=>(                        // loop
    a+=d,                           // move Alice
    a-=d*((a-l+1)%l?m[a]?0:q/l:~l), // wrap
    c=m[a],
    p=="&"?0:                       // do nothing after &
    d={">":1,"<":-1,"^":l,v:-l}     // set the new direction
      [c=="B"?r=0:c]                // if on Bob, r = 0
    ||d,
    p=c
  ))&&!r                            // return result

var testCasesTrue =
`A>B
-----------------
<BA
-----------------
A       B
-----------------
BA
-----------------
Av  >B
 >  ^
-----------------
Av
 B
-----------------
A>v
  >B
-----------------
A>v>   v>B
 v< > &<^
 > ^
-----------------
A>v>   v
 v< >B&<
 > ^
-----------------
A&<B
-----------------
A&B<
-----------------
<A       &B`
.split("\n-----------------\n");

var testCasesFalse =
`AvB
-----------------
A&B
-----------------
A><B
-----------------
A>v
 ^<B`
.split("\n-----------------\n");

var test = (cases, expected) => cases.map((t,i)=>++i+": "+(solution(t)==expected?"Pass":"Fail")).join`\n`;
document.write(`<pre>${test(testCasesTrue,true)}\n\n${test(testCasesFalse,false)}</pre>`);

Congratulations !

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Insert semi-sorted into unsorted array
Welcome to your first day at PPCG Inc. As our newest junior assistant document sorter, you are responsible for making sure all documents we sent down to you are archived in alphabetical order. It's so easy a monkey can do it. Well, metaphorically speaking, as we did hire a monkey to do it. Guess what? Turns out monkeys lack an understanding of our alphabet. Anyway, there's no time to fix the mess there is right now, so just try to not make the situation any worse, ok? Then get to it! If you get hungry, there's bananas over by the water cooler. Good luck!
Job Description
Input

You will receive a list of strings (the archive) and a string that needs to be added to that list (the document)
All strings will contain only uppercase letters, lowercase letters and spaces
Strings will always start and end with a letter

Task
Determine the target position of the document: the position it should receive in the archive. The target position can be determined as follows:

For each position:

Count the amount of strings in the archive before that position that are alphabetically before the document
Count the amount of strings in the archive after that position that are alphabetically after the document
Define the score of the position as the sum of the above two counts

The target position of the document is the position with the highest score
In case of a tie, all positions with the highest score are equally valid as target position. Only one needs to be selected.

When sorting:

Uppercase and lowercase letters are equivalent
Spaces come before letters

Output

The archive with the document added to it in any form

OR

The target position of the document, in either a 0-based or 1-based index

Job evaluation
Fewest bytes wins!
Example I/O
Archive:
    Applebuck Season
    Friendship is Magic
    The Ticket Master
    Griffon the BrushOff
    Boast Busters
    Bridle Gossip

Document: Dragonshy

Position scores (0-based index):
0: 0 + 3 = 3
1: 1 + 3 = 4
2: 1 + 2 = 3
3: 1 + 1 = 2
4: 1 + 0 = 1
5: 2 + 0 = 2
6: 3 + 0 = 3

Target position: 1

Welcome to PPCG, this seems like a nice first post! :) Your instructions in the "Task" section are kind of hard to read, though. Horizontal scrolling is annoying:I'd consider using a bullet list instead. We have a handy Sandbox where you can post challenges for the community to review, if you want.

Dragonshy I just got it! Very nice :-D

@Lex It would be good to have one or two more test cases

JavaScript (ES6), 81 bytes
(a,d)=>a.map((e,i)=>d[l="toLowerCase"]()<e[l]()?s--:++s>m&&(++m,p=++i),m=s=p=0)|p

Ungolfed:
function position(archive, document) {
    var score = 0;
    var max = 0;
    var pos = 0;
    var i = 0;
    while (i < archive.length) {
        if (archive[i++].toLowerCase() > document.toLowerCase()) {
            score--;
        } else {
            score++;
            if (score > max) {
                max++;
                pos = i;
            }
        }
    }
    return pos;
}

Edit: Saved a lot of bytes thanks to @user81655.

Also replacing the indexOf with a result variable that is set during the map would be shorter as well.

Agreed, but it hardly looks like my solution any more...

Pyth, 40 38 bytes
Credits to @Katenkyo for teaching me that A xnor B is basically A==B. (A xor B is also A!=B)
AQJ+],k0.e,rb0hkGteh.Msmq<hdrH0<edeZJJ

Try it online!
How it works:
It sums the XNOR of whether the entry is smaller than the document, and whether the entry's index is smaller than the document's index.
It finds the position in which this sum is the maximum, then outputs it.

Python 3, 135 167 Bytes
def a(b,c):a=[sum(map(lambda x:x.lower()>c.lower(),b[i:]))+sum(map(lambda x:x.lower()<c.lower(),b[:i]))for i in range(0,len(b)+1)];b.insert(a.index(max(a)),c);print(b)

Pyth, 54 52 47 45 bytes
AQVhlG=Ys+m>rH0rd0:G0Nm<rH0rd0gGNI>YZ=ZY=kN;k

Expect input is a list, first element is a list of strings (archive), second element is a string (document)
AQ                                            # initialize G and H with the archive and the document
  VhlG                                        # iterate over the indexes on archive
      =Ys+                                    # concatenate and sum the following scores
          m>rH0rd0:G0N                        # map a string comparison between the document and the archives up to the index, returning true(1) for lower, and false(0) for higher
                      m<rH0rd0gGN             # same as above, but starts at the index and goes up to the end of the archive, returning false(0) for lower, and true(1) for higher
                                 I>YZ         # Check if score is higher than highest
                                     =ZY      # update highest score
                                        =kN;  # update index
                                            k # print index

Test here

 Saved 5 bytes on input initialization (thanks @Kenny Lau)

Z is autoinited to 0 which if I'm reading your code correctly can save you a space

Using ["Applebuck Season","Friendship is Magic","The Ticket Master","Griffon the BrushOff","Boast Busters","Bridle Gossip"]\n "Dragonshy" as input and using E instead of @Q0 and @Q1 can save you four bytes.

You could use AQ instead of J@Q0K@Q1.

Ruby, 97 bytes
Anonymous function, returns the target position.
->a,d{d.upcase!;(0...a.size).max_by{|i|a[0,i].count{|s|s.upcase<d}+a[i..-1].count{|s|s.upcase>d}}}

When actually inserting into the archive, 110 bytes:
->a,d{t=d.upcase;a.insert (0...a.size).max_by{|i|a[0,i].count{|s|s.upcase<d}+a[i..-1].count{|s|s.upcase>d}},d}

MATL, 32 bytes
hk4#S4#S%2#0)>t0whYsw~0hPYsP+K#X>

Input is a cell array of strings (several strings separated by spaces and enclosed in curly braces) for the archive, and a string for the document. Output is 1-based. In case of a tie the first position is returned.
Try it online!
Explanation
h      % Concatenate archive and document as a cell array of strings
k      % Convert all strings to lowercase
4#S    % Sort and output the indices of the sorting
4#S    % Again. This gives the indices that applied to the concatenated
       % array would make it sorted
2#0)   % Separate last index (document) from the others (archive)
>      % Is it greater? Gives zero/one array the size of the archive
t      % Duplicate that array
0wh    % Prepend a 0
Ys     % Cumulative sum. This is first part of the score
w~     % Swap. Negate zero/one array
0h     % Postpend a 0
PYsP   % Reverse, cumulative sum, reverse. Second part of the score
+      % Add. This is the score of each position
K#X>   % Arg max

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Split string into n pieces (or pieces of length n)
The Challenge
In this challenge you have to do two different (but related) tasks depending of the order of the input.
Your program will recieve a string s and an integer n as input and will

split s into pieces of length n if s comes first. The last element will be shorter if necessary.
split s into n pieces of equal length if n comes first. If len(s) is not a multiple of n the first len(s) mod n elements will be one longer.

You may only take those 2 inputs. s will never contain only digits.
Notes

You may use the reverse mapping. Note this in your answer if you do that.
s will only contain printable ASCII characters (no newlines).
You may not use any builtins that solve either those two tasks directly. All other builtins are allowed.
You have to take both arguments from the same source.
You may take the arguments in an ordered list or any other format which clearly indicates their order as long as it is unambiguous.
You may take the input as one string/ stream and use a character which is not a valid input (like a nullbyte) to separate them.
n will always be equal or less than the length of s and greater than zero.
You may output the resulting list in any resonable format as long as it clearly indicates the particular pieces and their order.

Example
Input: programming, 3
The last element contains only 2 characters, because 11 is not divisible by 3.
Output: ["pro", "gra", "mmi", "ng"]
Input: 3, programming
11 is not a multiple of 3, so the first 2 elements will be one longer:
Output: ["prog", "ramm", "ing"]
Rules

Function or full program allowed.
Default rules for input/output.
Standard loopholes apply.
This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases
The test cases got generated with this Pyth program (uses builtins, so no valid answer). Thanks to @FryAmTheEggman for providing the base version of that!

3, helloworld -> ['hell', 'owo', 'rld']
helloworld, 3 -> ['hel', 'low', 'orl', 'd']
1, programming -> ['programming']
programming, 1 -> ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
8, programming -> ['pr', 'og', 'ra', 'm', 'm', 'i', 'n', 'g']
programming, 8 -> ['programm', 'ing']
9, code golf -> ['c', 'o', 'd', 'e', ' ', 'g', 'o', 'l', 'f']
code golf, 9 -> ['code golf']
4, 133tspeak -> ['133', 'ts', 'pe', 'ak']
133tspeak, 4 -> ['133t', 'spea', 'k']

Happy Coding!

You may not use any builtins that solve those two tasks. Does that include other built-ins, such get every n-th character from a string or split at occurrences?

@Dennis This was just meant to rule out builtins that solve this directly. I clarified.

If our language does not support arrays, how should we output? Would a newline between each result of the string be acceptable?

Also, for languages where the input is an array of ambiguous numbers, what should the procedure be?

@CᴏɴᴏʀO'Bʀɪᴇɴ Can't happen. s will never contain only digits. Also You may output the resulting list in any resonable format as long as it clearly indicates the particular pieces and their order which includes multiline output of course.

@DenkerAffe Let me clarify. The input to the program 65, "Hello!" would be read by the program as 65,72,101,108,108,111,33, so it cannot disambiguate which is the string and which isn't. To compensate, could one take a number that represents the order of the arguments? So the input could be 1 <n> <s> or 0 <s> <n>. Secondly, you say the input can have printable ASCII characters, including newlines, which would make my output ambiguous as well.

@CᴏɴᴏʀO'Bʀɪᴇɴ I don't count newlines as printable ASCII, so thats one problem solved. However, taking a number which indicates the input order would be a huge advantage, so I can't really allow that, sorry.

Let us continue this discussion in chat.

I assume the answer is no, but can builtins that solve one task be used to solve the other?

MATL, 46 26 21 27 29 42 bytes
jtU?jtbUe!tn2Gn>?0t(]tgbw(}ie]!2t$X{Oc''Zt

Try it Online! (Updated slightly to work with the latest version of the language)
Explanation
j           % Explicitly grab the first input as a string
t           % Duplicate
U           % Attempt to convert it to a number
?           % If the conversion to a number was successful
    j       % Explicitly grab the second input as a string
    t       % Duplicate the value
    b       % Bubble-up the first element in the stack
    U       % Convert to a number from a string
    e       % Reshape the string into a nGroup x nPerGroup matrix
    !       % Take the transpose
    t       % Duplicate the result
    n       % Number of characters in the repmat result
    2Gn     % Number of characters in the string
    >?      % If chars in repmat > chars in string
        O   % Zero
        t   % Duplicate
        (   % Assign the last element to a null character (bug in MATL)
    ]       % End if statement
    t       % Duplicate this matrix
    g       % Convert to a logical matrix
    b       % Bubble-up the original string
    w       % Flip the top two elements
    (       % Assign the non-empty characters to the chars from the input string
}           % Else the string comes first
    i       % Explicitly grab the second input (the number)
    e       % Reshape the characters into an nPerGroup x nGroup 2D array
]           % End of if statement
!           % Take the transpose so it reads left-to-right
2           % Number literal
t           % Duplicate
$X{         % Call num2cell to convert to a cell array
Oc          % Null character
''          % Empty string
Zt          % Replace null chars with empty strings
            % Implicit display of stack contents

What are those unprintables that appear at the end of some list elements? Those are not part of the input and should therefore not be part of the output either.

Isn't e a prohibited builtin ?

Maybe replace XUZN?... by U?... and swap the two if branches. Also, you don't need the 3$

@DenkerAffe Sorry about that. Should be fixed now.

@FliiFe Based on the comments on the initial post, e doesn't directly solve the problem, so I don't consider it to be prohibited, no.

@LuisMendo Thanks! I had that at one iteration or another but it must have gotten lost.

@Suever Are you sure? I still see them in the online interpreter.

@DenkerAffe Thanks to you we found a bug in MATL! Also, apparently null characters are displayed differently across browsers. It is now fixed!

JavaScript (ES6), 132 bytes
(s,t)=>+t?[...Array(-~(~-s.length/+t))].map((_,i)=>s.substr(i*t,t)):[...Array(s=+s)].map(_=>t.slice(p,p-=~((t.length-p-1)/s--)),p=0)

This is probably hopelessly over-engineered.

Well, my (now deceased) solution was grossly under-engineered. +1 for you

JavaScript (Firefox), 88 87 bytes
a=>b=>(s=+b?a:b,i=x=0,l=s.length,[for(c of s)if(r=s.slice(x,x+=+b||l/a+(i++<l%a)|0))r])

Call it like (...)("programming")(3) using Firefox 30+.

AWK, 121 130 128 122 Bytes
$1~/^[0-9]+$/{s=1}{a=$(s+1)
b=s?$1:$2
$0=""
for(j=-b;j<=c=length(a);)$0=$0 substr(a,j+=b+s,b+(s=s&&j<c%b*(b+1)?1:0))" "}1

The only issue is if the first entry is a string that starts with a numeric value.  This would cause AWK to see the string as that number and the second entry as the string.
OK... fixed the numeric issue, but it added 9 bytes :(.
Reworked a bit to save a couple bytes.
Almost back to the original length. :)

OK, @DenkerAffe , fixed it to work in general and only (eventually) added 1 byte.

Ruby, 119 bytes
->x,y{r=[t=0];x.to_s==x ?(r.push x[t...t+=y]while x[t]):x.times{r.push y[t...t+=y.size/x+(r[y.size%x]? 0:1)]};r[1..-1]}

And I take first place by 2 bytes...

Regex objects in Ruby can have values injected into them the same way strings can, so x.scan(/.{,#{y}}) works just as well for splitting the strings in the first case. Or does that count as a builtin?

Haskell, 131 bytes
import Data.Lists
q(d,m)=splitPlaces$(d+1<$[1..m])++[d,d..]
a#b|all(`elem`['0'..'9'])a=q(divMod(length b)$read a)b|1<2=q(read b,0)a

Usage example:
*Main> "8" # "programming"
["pr","og","ra","m","m","i","n","g"]
*Main> "programming" # "8"
["programm","ing"]

How it works: the main work is done by the helper function q which takes a pair of numbers (d,m) and a string s. It first builds a list of m times d+1 followed by infinite many d (e.g (1,3) -> [2,2,2,1,1,1,1,1,...]). It then uses splitPlaces to split s into chunks of lengths given by the list. splitPlaces stops if s runs out of elements, so an infinite list is fine.
The main function # checks which parameter is the number n / string str and calls q with either (div (length str) n, mod (length str) n) or (n, 0) plus str.

Pyth, 181 bytes
Let's pretend the longest code in bytes wins \o/
DyGK@G0J:@G1"."1=YJV%lJKW<l@YN.EclJK=YXYN+@YN@YhN=Y.DYhN)FNr%lJK/-lJ%lJK/-lJ%lJKKW<l@YNsclJK=YXYN+@YN@YhN=Y.DYhN))RY)DPG=K@G1=J:@G0"."1=YJV/lJKW<l@YNK=YXYN+@YN@YhN=Y.DYhN))RY).xyQPQ

Try it here ! (The online interpreter seem to have a bug, it displays the input while it should not)
Here's the output from the terminal:
» pyth split.pyth <<<'["helloworld", 3]'
['hel', 'low', 'orl', 'd']
» pyth split.pyth <<<'[3, "Helloworld"]'
['Hell', 'owo', 'rld']

Seriously, I am open to new approach. I'm new to python, so I probably missed a few shorthands.
I mean, I think my answer is deseperate from the point it is longer than the javascript answer...

Can you provide a sample input and output?

Note the official solution under the header testcases. The testcases are generated by Pyth. The solution is .xcsJKcJsK, where J and K are the two arguments.

@KennyLau I added a link to the online pyth interpreter. Strangely, it outputs the input too while I'm sure it did not yesterday... Will try to fix that.

use spaces to suppress printing

@KennyLau spaces where ?

"J" would print while " J" would not. Spaces before the expression.

@KennyLau The problem is to figure out the expression that prints. It works on my computer without additional printing

Do you have debug mode? You can see which expression prints in debug mode.

@KennyLau Now it works (without modification). I really think it was a bug with the online interpreter.

C# (LINQPAD) - 335 bytes
var y=Util.ReadLine().Split(',');int x,j=0;var t=int.TryParse(y[0].Trim(),out x);x=x==0?int.Parse(y[1].Trim()):x;var i=t?y[1].Trim():y[0];var z="";if(!t){while(i.Substring(j).Length>x){z+=i.Substring(j).Length>x?i.Substring(j,x)+", ":"";j+=x;}z+=i.Substring(j);}else z=string.Join(", ",i.Split(x).Select(s=>string.Concat(s)));z.Dump();

The input reading part took up a bit of space. Winner of longest answer.
Usage #1:
$ 3, helloworld

>> hell, owo, rld

Usage #2:
$ helloworld, 3

>>hel, low, orl, d

owo what's this?

PHP, 114 bytes
[$t,$n,$p]=$argv;for(@+$p?$s=$n:$f=$n*($p=strlen($s=$p)/$n)%$n;$t;)echo$t=substr($s,$a+=$e,$e=$p+($i++<$f)|0),"
";

String should not start with digits.
(Replace +@$p with is_numeric($p) to fix.)
Output should not contain a chunk "0".
(Insert ~ for printable ASCII, a& for any ASCII before $t; to fix.)
Run with -nr or try it online.

PowerShell, 122 118 bytes
param($a,$b)if($a-is[int]){$a,$b=$b,((($l=$b|% Le*)-($c=$l%$a))/$a)}$a-split("(..{$b})"*$c+"(.{0,$b})"*$a.Length)-ne''

Try it online!
Less golfed:
param($a,$b)
if($a-is[int]){
    $length=$b|% Length
    $c=$length%$a
    $a,$b=$b,(($length-$c)/$a)  # recalc length and swap
}
$pattern="(..{$b})"*$c+"(.{0,$b})"*$a.Length
$parts=$a -split $pattern       # pattern like '(..{3})(..{3})(.{0,3})(.{0,3})(.{0,3})'
$parts -ne ''                   # output not empty parts

Ruby, 69 bytes
->a,b{a.scan /.{1,#{b}}/ rescue b.scan /.{1,#{b.size.fdiv(a).ceil}}/}

Attempt This Online!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Ponderous primality testing
One of my favorite algorithms was posted on Stack Overflow as an answer to What is the fastest way to generate prime number recursively?. In pseudocode:
Nathan's algorithm
bool isPrime(int n):
    if (n < 2) return false
    for p in 2..n-1:
        if (isPrime(p) && n%p == 0) return false
    return true

This program is lovely because it doesn't have any wasted steps (in the author's words, "it's quite efficient because it only needs to test the prime factors") but still manages to take far longer than any reasonable algorithm. For example, compare the naive algorithm:
Unoptimized trial division
bool isPrime(int n):
    if (n < 2) return false
    for p in 2..n-1:
        if (n%p == 0) return false
    return true

This requires 10005 ≈ 104 divisions to test 10007, the smallest 5-digit prime. By contrast, Nathan's algorithm takes more than 10370 divisions, making it 10366 times slower. If every electron was a 1-googol GHz computer, and this program had been running across all electrons in the universe since the Big Bang, it wouldn't even be close to 1% done.

The task is to write a program, in the language of your choice to test if a given number is prime as slowly as possible. The programs may not simply waste time by idling or executing unused loops; it should be clever in its sloth.
Scoring
This is a popularity-contest, so the (valid) answer with the most votes wins. Golfing is neither required nor recommended. Suggested criteria for voting:

Creativity: How does the program manage to do so much work?
Originality: Does the program use a novel approach?
Reasonableness: Does the code look reasonable at a glance? It's best if there are not sections which could obviously be excised to speed it up.
Simplicity: A single, well-executed idea is better than a combination of unrelated ideas (though cleverly combining approaches is encouraged).

I consider Nathan's program to embody all four principles. As such, if the original author posts the original program here I will upvote it.

How does one determine idleness or useless code?

@CoolestVeto: It's a [tag:popularity-contest], that's up to the voters.

This could be a decent challenge, but it feels just a little bit too close to [tag:code-trolling].

@DrGreenEggsandHamDJ: The main focus is on inefficiency; making it looks reasonable is just an aesthetic bonus.

@DrGreenEggsandHamDJ: Oh, and thanks for the tag.

While this challenge doesn't bear the tag, it is arguably an underhanded contest, which are off-topic per community consensus.

@Dennis: I didn't intend it as that (as as such left off the tag). The main focus is on finding creative ways to delay the result.

@Dennis: I edited the question to clarify. Better now?

You scrubbed the word underhanded from the specification, but the intentions remain. If the reason for the code's slowness has to be obfuscated, the contest is underhanded.

@Dennis: (1) This was never intended as an underhanded challenge. (2) The code is not supposed to be obfuscated in any way -- I don't intend (and haven't intended) to vote for obfuscated code. (3) The only place I ever mentioned any of this was in the recommendations to voters -- they are entirely optional. The purpose of that bullet point was to encourage creativity, not to troll. (If I wanted to be underhanded I would ask for code which ran quickly for most inputs and slowly for a tiny fraction -- clearly code which runs at glacial speed would be discovered immediately on execution.)

Python 2, Really slow
import time

def isPrime(n):
    if type(n) is not int: return False
    if n < 2: return False
    if n == 2: return True
    has_composite_factor = False
    for i in range(2, n):
        i_is_prime = isPrime(i)
        if n % i == 0:
            if not has_composite_factor and i_is_prime:
                has_composite_factor  = True
    return not has_composite_factor

def time_it(n):
    start = time.clock()
    prime = isPrime(n)
    end = time.clock()

    return end - start

for i in range(20, 30):
    print "{}: {}".format(i, time_it(i))

If a number is prime, it stands to reason that all of it's factors must also be prime. If we can find a single composite factor, then this number cleary isn't prime. We must also check to see if the number is valid, which is why we check type(n) and n < 2.
This runs decently fast on n < 20 but takes several seconds once you hit 25. Here is how long it takes to calculate 20-30:
20: 0.141494
21: 0.282143
22: 0.565975
23: 1.132836
24: 2.266971
25: 4.525667
26: 9.050018
27: 18.110675
28: 36.372516
29: 72.920298


text:
What's being surrounded
I've always wanted to surround some text with #s, but I have trouble figuring out what I surrounded so in this challenge you'll be writing a program to do just that
Examples
Input / Outputs are separated by a newline.
###
#a#
###

a

 #
#a#
 #

a

  ###
 # a #
# b c #
#######

  a
 b c

ABCDHIJ
E####GK
F# M #L
#   N#O
P####

  M
   N

###A###
#C#B#o#
#d###e#
 # go#
  ###

C   o
d   e
  go

Spec

#s are what "surround" a block of text
# will always be adjacent to one another (including diagonally)
# will always form a closed shape
There will only be one # shape
In the event of a concave shape, holes should be filled with spaces.

Whitespace must be preserved in the output

at first I was like.. just take out the #s and there you go... and then it got hard.

I'm having trouble getting input in javascript and splitting by newline... how do I have to get input? could it be formatted with a \n after each line of input and passed as a function param to my program or what?

Whats is the set of valid input characters ?

Is there an error on the output of the MN example? Its output consists of only the text surrounded, _M_\n___N (using underscores instead of spaces because of formatting issues), while in the abc and Codego examples the output also includes whitespace where #s were in the input. If only the text surrounded by #s is to be printed, then the output of the abc example should be _a_\n_b_c_ (instead of __a_\n_b_c) and the output of the Codego example should be Co\nde\n_go (instead of C___o\nd___e\n__go).

@epidemian ah, nice catch. I've fixed the MN example. as there shouldn't of been an extra space after M.

You should make a harder example, like with a concave spiral or maze, so that any floodfills must be able to work around corners, rather than in straight lines from the edges.

Don't use flood fills.. just check if the char has a '#' anywhere left, right, above, and below it. Simple... but I guess I'm losing so...

@epicTCK: So how does your solution work if a character is in a twisty corridor that in the end connects to the outside? It will see a # in all directions.

meh. good point. But my program works for all the examples, and changing the examples now would invalidate it. so he can't/ shouldn't change them

@epicTCK your answer shouldn't just follow the examples it should fulfill the spec. If it doesn't please fix it

I'd have to write a completely new answer. ( I Might do that, the flood fill might bring the byte count down)

Perl, 144 138 132 129 128 127 126 124 bytes
Includes +2 for -p0
The code assumes \0 is not a valid input character (at least inside the #).
Run with the input on STDIN:
surround.pl < surround.txt

surround.pl:
#!/usr/bin/perl -p0
/^#[^#\0]/m&&s/^|[^#\n\0]\0/\0\0/mg,s%.%s/.(.*)/$+\0/g;/#/&&reverse"\n",/^./mg%seg until$?++<$$_++;y/\0/#/;s/^#*\n|#+$|^#//mg;y;#;

The code works as is, but replace the \0 and \n by their literal versions for the claimed score. Notice there is a space  at the end of the line. The code loops way too many times, so you may have to wait 30 seconds or so for output.
Explanation
I am going to do a floodfill with \0 stopped by # from the outside in the orthogonal directions. After that I will slice off the # sides and replace all that is left by spaces. To avoid having to handle all directions in the floodfill I will repeatedly rotate the target area and only floodfill from right to left
/^#[^#\0]/m                   The rotation is written such that it slices
                              off the first column. That is ok unless the
                              first column contains a # that is followed by
                              something that could be the inside. There is
                              no newline inside the [] because short lines
                              will get extended during the rotation and
                              the character following the # will end
                              up as a \0 and match in a later round
    &&s/^|[^#\n\0]\0/\0\0/mg  In case the # could be an interior border I
                              will add two columns of \0's in front. One
                              will be a sacrifice for the rotation, the
                              other column will end up at the end of the area
                              after two rotations and function as seed for the
                              floodfill. This regex also does one step of
                              the floodfill from the back to the front.
                              After a certain number of loops we are certain
                              to get to a first column that must not be
                              dropped so at some point the last column is
                              guaranteed to consist of only \0. And we only need
                              to fill backward since the rotations will make
                              any direction backward at some point

s%.%  process column  %seg    I will replace each character (including \n)
                              in the string by the next column in reversed
                              order or an empty string if there are no more
                              interesting columns. This is therefore a right
                              rotation. There are less columns than
                              characters so this loop is long enough

    s%.%s/.(.*)/$+\0/g        Remove the next (now first) character from each
                              row (so remove the column). Because the
                              original area is not necessarily a rectangle
                              add a \0 at the end of the row so we won't run
                              out out of columns (this would cause shorter
                              rows to have no entry in the new rotated row)
                              This will not do anything for empty lines so
                              they DO get squeezed out. But that is not a
                              problem since the problem statement says there
                              will be only one # shape so any empty lines
                              are can be safely dropped (this would not be
                              so if there could be multiple # shapes because
                              that could create a new surrounded area

    /#/                       Check if any of the remaining columns still
                              has a #. If not all remaining columns are on
                              the outside and can be dropped
       &&reverse"\n",/^./mg   Collect the column and add a \n to its reverse

 until$?++<$$_++              Keep doing this until we get to a multiple of
                              65536 rotations when $? waraps back around to 0
                              (this is a multiple of 4 so the area is left
                              unrotated) and an area we have seen before
                              ($$_ >= 1)
                              (so all slicing and flood filling is finished)
                              $_ having been seen in a previous rotations is
                              not a problem (though rather tricky to prove)

At this point e.g.
AB##J
E####GK
F# M #L
#   N#O
P####

will have been replaced by:
0000000
0####00
0# M #0
#   N#0
0####00

Basically all columns and rows that are not directly bordering the inside have been sliced off. Any outside characters left has been replaced by \0.
At the top and right there is an extra layer of \0. So all that is left is cleanup:
y/\0/#/                       Replace any outside that is left by #
s/^#*\n|#+$|^#//mg            Removes the first two and last line (the only
                              lines that can consist of purely #)
                              Removes any trailing #
                              Removes the first column of #
y;#; \n;                      Replace any remaining # by space since they
                              are needed to fill the concave parts
                              The final \n; is not written since it is implicit
                              in the -p loop

Do your floodfills work around interior corners, if there were any?

@mbomb007: Yes, since the area is repeatedly rotated, so it is able to follow any twisty corridors. The loop stopping too early before reducing very thick walls is the only flaw as far as I know

@mbomb007: Aaaaand the thick wall flaw is now solved

copy-pasting your solution as-is (not replacing the escaped chars), the output is merely the input with all # stripped. please verify my bash session: http://codepad.org/YbCzB4O4

@ardnew: Oops, sorry. For the last update did not repaste the full solution, and I should have replaced the while by an until. Fixed now, Please try again

It looks like say((s/#+[^#]+#+/v0 x$&=~y,,,c/egr^$_)=~s/#/ /gr) (with -p) should work but it doesn't. Maybe you can do something with that? I don't have time or, probably, ability.

@msh210: I don't think so. It seems to use a too simplistic idea about what is "inside" and "outside" (though something like it could be made to work for the given examples since they don't have any twisty corridors)

Javascript, 485 464 427 417 396 390 bytes

s='indexOf';k='lastIndexOf';h="#";t=b=>b[0].map((x,i)=>b.map(x=>x[i]));i=>{m=i.split`
`;for(h of m){m[m[s](h)]=h.split``;}for(y=0;y<m.length;y++){for(z=x=0;x<m[y].length;x++){if(m[y][x]==h)break;if(m[y][s](h)<x&&m[y][k](h)>x)z++;q=t(m);if(q[y][s]h)<x&&m[y][k](h)>x)z++;if(z>2)m[y][x]=h}}for(p of m){v=p.join``.match(/\S/);e=v?p.join``:'';m[m[s](p)]=e;}m=m.join`
`;return m.replace(#/g," ")}

Yes. I tried. And, although I am at 485 bytes, I am winning because no-one else felt like answering this question. So, hah!
And also, I am well aware that I could golf this loads, I just am tired at the moment...  well now I'm at 396 Thanks to Conor for most of the golfing... :D

Declare the variables inside the for loops outside with y=z=0


text:
Draw a spiral in a box

This geometric spiral looks complicated, but it's fairly simple to draw; take the following box:

Draw a straight line between the corner of the box and some set distance above the next corner counter-clockwise.

Continue this pattern inward, always staying that set distance away from the corner of the next line. Here's a few more lines in.

As you can see, as the pattern continues, the spiral approaches the center and the boxes you draw begin to rotate. Note that the distance remains constant, regardless of angle.
The Challenge
The Inspiration (and also thanks to the wonderful person who introduced me to this concept <3)
Given a numerical (possibly fractional) input from 1 to 25, write an image to disk that uses this pattern or display the output on the screen, where the distance from each corner is the distance of one initial side of the box divided by the input. Continue the pattern inward until the distance from the corner specified is longer than the length of the next side.
Rules

You may not use built-ins for this spiral creation, but you may use image processing builtins.
If you write to disk, you must output an image in any of .jpg, .gif, .tiff, .pbm, .ppm, and .png.
The initial side length must be at least 500 pixels.
The initial corner may be whichever you choose.
As always, the Standard Loopholes are disallowed.

Closely related.

Is there a minimum for how many levels deep this spiral must be?

@LegionMammal978 I would never ask for an input greater than 25, I'll add that.

Including .pbm or .ppm might help some of the less graphical languages.

also related

What if the screen isn't at least 500 pixels? Still no go?

@CᴏɴᴏʀO'Bʀɪᴇɴ You may assume that the screen is at least 500 pixels. :)

@CoolestVeto Haha! I meant on a calculator whose screen isn't that large.

@CᴏɴᴏʀO'Bʀɪᴇɴ Oh! Well, if you're using TI-BASIC, feel free to extend the borders and just make it 500 units tall instead. That's fine. :P

Is this about shortest possible code? I've read that nowhere, but the Shoes answer suggests so.

@BjörnKautler the tag [tag:code-golf] means that, yes.

Do I have to save it to disk or is displaying enough ?

@user7185318 It is sufficient to display the image.

Shoes (Ruby) 163 bytes
Shoes is a ruby-based GUI toolkit.
Shoes.app{n=ask('').to_f
r=s=5E2
a=[0,s*i="i".to_c,s*i+s,s,0]
(q=a[-3]-a[-4]
r=q.abs/s*n
a<<a[-4]+q/r)while r>1
1.upto(a.size-1){|j|line *(a[j-1].rect+a[j].rect)}}

Ungolfed
Shoes.app{
  n=ask('').to_f                 #Open a dialog box with no message, get n from user
  r=s=5E2                        #Initialize s to sidelength=500. r can be initialized to any vale, we use the same one for convenience.
  a=[0,s*i="i".to_c,s*i+s,s,0]   #intialize array a with 5 points needed to draw a square, in complex number format (first point=0 is duplicated.)

  (
    q=a[-3]-a[-4]                #find the vector from point plotted 4 before to the following point (plotted 3 before)
    r=q.abs/s*n                  #r is the scale factor
    a<<a[-4]+q/r                 #add a new point derived from a[-4] by moving toward a[-3] by a distance s/n
  )while r>1                     #break loop when length of line is less than s/n

  1.upto(a.size-1){|j|           #for all points except 1st and last one
    line *(a[j-1].rect+a[j].rect)#take the two complex numbers correspondimg to the current and previous point,
  }                              #convert to 2-element arrays (rectangular coordinates
}                                #combine to make a 4-element array, use * to splat into 4 parameters, and draw using the line method.

Outputs n=4 and n=25

Note that the shape always ends in a triangle, which collapses further to a line. Replacing size-1 with size makes no difference to the appearance of the output and would save 2 bytes, but I left it in for theoretical correctness.
Output n=300
Inspired by a comment by OP, the higher numbers do look great!

Is the space following line in the bottom line necessary?

@CoolestVeto unfortunately yes. the * converts the four element array formed by conversion of the complex numbers into four parameters for line. The standard syntax is line(*(a[j-1].rect+a[j].rect)) so removing the parentheses and adding a space is already  a saving of one byte. Removing the space makes Ruby try to multiply line by the contents of the parentheses, which makes no sense and causes it to throw an error. There is some golfing to be done here, just not that. I'll look into it later.

I'm almost certain you can get rid of the parens around the argument to upto. Also, have you tried removing the ('') after ask? I haven't tested it, but it may be unnecessary

@QPaysTaxes unfortunately neither of those works.

The output for 100 is beautiful.

@CoolestVeto I find n=100 a little disturbing; it jumps out and goes all 3D on me. I've posted n=300 which is darker overall and therefore calmer.

Java, 1056 1005 985 948 522 508 507 504 502 501 493 492 488 474 465 458 bytes
import java.awt.*;interface G{static void main(String[]a){new Frame(){int s=499,o=s,e,i,x,y;{o/=new Float(a[0]);add(new Component(){public void paint(Graphics g){g.drawRect(0,0,s,s);int[]p={s,s,s,0,0,0,0,s};for(double d=s,t;d>o;t=o/d,i=e*2,x=(int)((1-t)*p[i]+t*p[(2+i)%8]+.5),y=(int)((1-t)*p[1+i]+t*p[(3+i)%8]+.5),g.drawLine(p[(6+i)%8],p[(7+i)%8],x,y),p[i]=x,p[1+i]=y,e=++e%4,i=e*2,x=p[(2+i)%8]-p[i],y=p[(3+i)%8]-p[1+i],d=Math.sqrt(x*x+y*y));}});show();}};}}

Thanks to CoolestVeto and ECS for yet other ways to reduce size. :-)

Ok, I golfed it down a bit, but there is more possible for sure, I coded too object-oriented to be character-minimalistic :-D

@AlexA. If I later on improve my code and make it shorter, can i then simply update the post with the shorter version?

@BjörnKautler Yup, that's good! :) I'm working on a few places to shorten right now.

@BjörnKautler You certainly can!

Is it ok if the user has to enlarge the window to see the complete output, or does the window has to be large enough to show the output?

@BjörnKautler I don't see an issue with that. Removing the .pack()?

You can remove my "suggested edit" thingy if you want and just let that be the code, if you desire.

Yep, I meant the pack. :-)

I'll let it there for now, but I think I'm already way shorter. Most probably nowhere near the Shoes answer, but definitely shorter. :-)

Hm, how much rounding error is acceptable? Through size-optimizations my center is off the middle, the more the higher the input is. Replaced some Math.round() by (int)

I think now there is not much more possible without a different algorithm or with introducing the rounding error, removing the x/y rounding. @CoolestVeto you are welcome to golf it more if you can now. :-)

Wow, I've never seen more than 500 bytes chucked off an answer. :O

Ah, the good old deprecated show(), thanks. Calculate in the first post, there it was 7959 :-D

You can use new Float(a[0]) instead of Float.parseFloat(a[0])

@ECS ah, good point, thanks, answer updated

Groovy, 412 411 403 398 bytes
import java.awt.*
new Frame(){
def s=499,o=s/(args[0]as float),e=0,i,a,b,d,t
{add new Component(){void paint(Graphics g){g.drawRect 0,0,s,s
p=[s,s,s,0,0,0,0,s]
for(d=s;d>o;d=Math.sqrt(a*a+b*b)){t=o/d
i=e*2
a=(int)((1-t)*p[i]+t*p[(2+i)%8]+0.5)
b=(int)((1-t)*p[1+i]+t*p[(3+i)%8]+0.5)
g.drawLine p[(6+i)%8],p[(7+i)%8],a,b
p[i]=a
p[1+i]=b
e=++e%4
i=e*2
a=p[(2+i)%8]-p[i]
b=p[(3+i)%8]-p[1+i]}}}
show()}}

I have problems to make it run with groovy 2.4.4  :  Caught: groovy.lang.MissingMethodException: No signature of method: static s.div() is applicable for argument types: (java.lang.Float) values: [25.0] Possible solutions: is(java.lang.Object), wait(), run(), run(), find(), any() groovy.lang.MissingMethodException: No signature of method: static s.div() is applicable for argument types: (java.lang.Float) values: [25.0] Possible solutions: is(java.lang.Object), wait(), run(), run(), find(), any()  at s$1.<init>(s.groovy:3)  at s.run(s.groovy:2)

With 2.3.9 it works fine for me.