text:
Format a floating point number exactly as decimal
Any binary floating point can be formatted exactly in decimal. The resulting string might be somewhat long, but it is possible. In my article on floating point I cover the importance of precision, and now I want this function. This challenge is to write a program, or function, that takes a floating point value as input and formats an exact decimal string as output.
To ensure we are working with the correct floating point numbers a precise format must be provided as input to the program. This format will be two integers Significand Exponent, where the actual floating point value is Significand * 2 ^ Exponent. Note that either value can be negative.
Specifics:

The range and precision of at least a 32-bit float must be supported (no input will go beyond that)
The decimal formatted value must be an exact representation (simply close enough to guarantee a correct round-tip back to float is not good enough)
We don't trust standard library floating point formatting functions to be correct enough nor fast enough (ex: printf), and thus they may not be used. You must do the formatting. Integral formatting/conversion functions are allowed.
There may not be any leading or trailing zeros, except for the required one leading zero in front of the . if there is no whole number component
A function, or whole program, is allowed.

Examples:
1 -2 => 0.25
17 -3 => 2.125
-123 11 => -251904
17 50 => 19140298416324608
23 -13 => 0.0028076171875
3 120 => 3987683987354747618711421180841033728
3 -50 => 0.00000000000000266453525910037569701671600341796875
-3 -50 => -0.00000000000000266453525910037569701671600341796875
10 -2 => 2.5
-12345 -3 => -1543.125
0 0 => 0
161 -4 => 10.0625
512 -3 => 64

Shortest code wins.

Is the use of unlimited precision floating point arithmetic allowed?

If the exponent is nonnegative, can we end with .0?

@Dennis: Yes, unlimited or high fixed precision arithmetic is allowed.

@Sp3000: No, that's a trailing zero and is disallowed. I think a trailing . should also be disallowed.

May I suggest adding the test case -3 -50? There are no test cases where both numbers are negative and my first submission broke on it.

Added the test case. If anybody else has any test cases that trip up their code please list them in case they can also trip up other solutions as well.

I think that's inconsistent. If 0.abc is not a leading zero, then abc.0 isn't a trailing one.

I suggest adding cases 10 -2 and -12345 -3

@orlp: It's just convention when writing numbers to not lead with . but to always put a 0 in the front.

It's also convention to always end with .0 for whole numbers when dealing with floating point numbers. See for example Python: str(1.0) == '1.0' versus str(1) == '1'. Your logic is still inconsistent.

@orlp Maybe the OP prefers JavaScript style formatting :) Anyway, he has the right to define the requirements (and you have the right to raise your concern too)

Another case suggestion: 0 0 (not sure if other exponents are needed)

And another case: 161 -4 (zero before and after decimal point but not starting with 0)

Proposed test case: 512 -3. Negative exponent, but result has no fractional part.

CJam, 43
r_'-&\ize999rim<s1e3'0e[W%999/(i_L?\+'.*sW%

Try it online
Explanation:
The program works with exponents up to ±999, close to double precision (64 bit). It separates the minus sign (if present) from the significand, multiplies it by 10999 then does a bit shift with the exponent, which is now an exact calculation. It then pads to the left with zeros if the result has less than 1000 digits, separates the last 999 digits as the fractional part, removes trailing zeros by converting its reverse to integer, adds a decimal point if needed, and puts everything back together.
r_         read and duplicate the significand in string form
'-&        keep only the minus sign, if present
\          swap with the other copy of the significand
iz         convert to integer and get absolute value
e999       multiply by 10^999
ri         read the exponent and convert to integer
m<         shift left by it; negative values will shift right
            the result is an exact non-negative integer
s          convert to string
1e3'0e[    pad to the left with zero characters up to length 1000
            longer strings will be left intact
            we need 1 more than 999 for the 0.xxx case
W%         reverse the string
999/       split into slices of length 999
(          take out the first slice (reversed fractional part)
i          convert to integer
            this removes the leading zeros (trailing in reverse)
_L?        if it's zero, replace with an empty string
\+         concatenate back (to the left) with the second slice
'.*        join the with the dot character
            if the fractional part was zero, we only have the second slice
            (reversed integer part) and there is nothing to join
s          convert to string; this is the reversed result without the sign
W%         reverse back

At the end, the minus sign (if any) and the final string are automatically printed together.

CJam, 50 bytes
q~A1$z#\_0>K5?\z:E#@_s'-&oz*\md_sE'0e[W%isW%'.\+Q?

This is a full program that reads from STDIN. Try it online in the CJam interpreter.
Verify all test cases at once.

Based on your comment I assume CJam has unlimited precision and you've used that here? Is it correct then that this answer covers any input, not just 32-bit float? Also, can we get an explanation of how it works?

CJam has unlimited precision for integers, but only double precision floats. I multiply by a power of 20 for positive exponents and a power of 5 for negative ones, the cast to string and insert the dot. I'll add a detailed explanation in a few hours.

And yes, given enough memory, this should work for any input.

10 -2 seems to have a trailing zero

@aditsu: Ah yes, one trailing zero for every power of 2...

@aditsu: Fixed at the cost of 5 bytes. :(

Can you check -12345 -3 ?

@aditsu: Checked and fixed at the cost of 0 bytes.

GNU sed + dc, 65
Score includes +1 for sed's -r option.
y/-/_/
s/.*/dc -e"C8k& 2r^*p"/e
s/\\\n//
s/0+$//
s/^(-?)\./\10./

I was tempted to claim this dc-only answer C8k& 2r^*p for a score of 10, but dc has some formatting quirks:

the -ve sign is _ instead of -
long lines are broken with backslashes
trailing zeros must be removed
leading 0 for |n| < 1 must be added

So the dc expression is wrapped and evaled by sed to take care of the above.
Test output:
$ echo "1 -2
17 -3
-123 11
17 50
23 -13
3 120
3 -50
-3 -50
8388608 127
1 -127" | sed -rf float.sed
0.25
2.125
-251904
19140298416324608
0.0028076171875
3987683987354747618711421180841033728
0.00000000000000266453525910037569701671600341796875
-0.00000000000000266453525910037569701671600341796875
1427247692705959881058285969449495136382746624
0.0000000000000000000000000000000000000058774717541114375398436826861112283890933277838604376075437585313920862972736358642578125
$

Hmm, I'm thinking that dc kind of violates my rule on using a standard formatting function.

@edA-qamort-ora-y I figured that use of dc is ok, given "unlimited or high fixed precision arithmetic is allowed".  dc's p command is not a "floating point formatting function" - it is an arbitrary precision print function.  I am setting the precision to 128 decimal places (C8k), which I think is more than enough for any 32bit float.


text:
Incremental Game Time Format
Incremental Game Time Format
Goal
Incremental games often have a countdown timer expressing the days, hours, minutes and seconds until a task is complete.  Depending on the space available, they can be formatted as:
2d 13h
23h 59m 48s
14m
3h 0m 0s

The goal of this code golf is to write a function or program that performs this formatting.
Inputs

The total number of seconds.
The maximum number of segments to output.

Output

Segments include:

0w weeks
0d days
0h hours
0m minutes
0s seconds

Each segment is separated by a single space.
Displayed segments must be contiguous.  For example, you will not show hours and seconds without showing minutes, even if there are zero minutes.
Single-digit values do not have leading zeros, though a value of zero must be shown as 0.
Values are rounded down.
The first segment displayed is the first non-zero value.

Test Cases
seconds  segments  output
     0      1      0s
   123      1      2m
   123      2      2m 3s
   123      3      2m 3s
 82815      3      23h 0m 15s
307891      2      3d 13h
307891      4      3d 13h 31m 31s
604800      1      1w
604800      6      1w 0d 0h 0m 0s

Winning
The lowest byte-count solution in one week will win "acceptance".
Edits

Clarified which segment is first, as shown in examples.
Added test case 4 as per request.

What is expected output for 307891    1? 0w or 1w.

@jnovacho Wouldn't it be 3d? "The first segment displayed is the first non-zero value"

@Luigi True. I've missed that.

Am I the only one thinking that this is a "could some one please write this code for me" question?

It's not every day a code golf task might actually be useful. I say go with it :D

@fho, if I wanted to write this function for production code, I would be writing it maintainable, not golfing it.  ;-P

@Hand-E-Food point taken ;)

CJam (snapshot), 41 38 bytes
q~"<<^X^G"{imd\}%W%"wdhms":s.+_{0=}#><S*

The above uses caret notation, since two of the characters are unprintable.
Thanks to @Sp3000 for golfing off 2 bytes.
Testing
The latest stable release (0.6.5) has a bug that can cause {}# to return Integers instead of Longs. Quite paradoxically, this can be circumvented by casting to integer (i).
To run this with code with the online interpreter, click this permalink or copy the code from this paste.
Alternatively, you can download and build the latest snapshot by executing the following commands:
hg clone http://hg.code.sf.net/p/cjam/code cjam-code
cd cjam-code/
ant

You can create the CJam file like this:
base64 -d > game-time.cjam <<< cX4iPDwYByJ7aW1kXH0lVyUid2RobXMiOnMuK197MD19Iz48Uyo=

How it works
q~        e# Read an evaluate the input.
"<<^X^G"  e# Push the string corresponding to the array [60 60 24 7
{         e# For each character:
  i       e#   Replace it by its code point.
  md      e#   Push divisor and residue of the division by that code point.
  \       e#   Swap their order.
}%
W%        e# Reverse the resulting array.
"wdhms":s e# Push ["w" "d" "h" "m" "s"].
.+        e# Perform vectorized concatenation.
_         e# Push a copy.
{0=}#     e# Find the index of the first pair with positive integer.
>         e# Remove the preceding pairs.
<         e# Truncate to the number of pairs specified in the input.
S*        e# Join, separating by spaces.

Java, 197 191 bytes
String p(int s,int m){String a[]={s%60+"s",(s/=60)%60+"m",(s/=60)%24+"h",(s/=24)%7+"d",(s/7)+"w"},b="",z="";for(s=5;s>0&&a[--s].charAt(0)=='0';);for(;s>=0&&--m>=0;z=" ")b+=z+a[s--];return b;}

I just noticed that Java supports declaration like String a[]. This allowed me to pull the declaration of b and z into the same line, which saved me from writing String again.

Like the ;z=" ") - very clever.

C, 134 127 110 104 103 bytes
New Version:
a,e=5;f(n,x){for(;e;n%=a)a=(int[]){1,60,3600,86400,604800}[--e],x>e?printf("%u%c ",n/a,"smhdw"[e]):0;}

Previous Version:
#define p(a) x>--e?printf("%u%c ",n/a,"smhdw"[e]):0;n%=a;
e=5;f(n,x){p(604800)p(86400)p(3600)p(60)p(1)}

Pyth, 39 43 bytes
jd_>vz+V?u?GeGPG+m%~/QddCM"<<"Q)Q]0"smhdw

edit: +4 chars, because I forgot the 0s test case.
This includes 2 unprintable chars. Get the actual code and try it online: Demonstration
Explanation:
                                         z = 1st input line (segments, as string)
                                         Q = 2nd input line (time, as int)
                         "<<.."          string with 4 chars
                       CM                convert to ASCCI-values => [60,60,24,7]
                m                        map each d of ^ to:
                   /Qd                     Q / d
                  ~                        update Q, but use the old value for
                 %  Q d                    Q mod d
                                         this gives [sec, min, hour, day]
               +               Q         add Q (week)
        u                       )        apply the following expression to G,
                                         starting with G = [s,m,h,d,w], until
                                         G stops changing:
         ? eG                              if eG != 0:
          G                                  update G with G (stop changing)
                                           else:
             PG                              update G with G[-1]
                                         this gets rid of trailing zeros
      +V                         "smhdw  vectorized add with "smhdw"
   >vz                                   only use the last eval(z) items
  _                                      reverse order
jd                                       join by spaces and print

Python 2.7 - 181 178 174 bytes
My first attempt to golf something.
def I(s,M):
 z=[0]*5;j=0
 for i in [604800,86400,3600,60,1]:z[j],s=s/i,s%i;j+=1
 l=[z.index(n)for n in z if n][0]
 return" ".join([str(i)+n for n,i in zip('wdhms',z)][l:l+M])

Great first attempt! Better than some of my sixth attempts... ;) You can cut off 3 bytes by changing if n!=0 to just if n.

Oh yeah, forgot that 0 evaluates to False. Thanks.

Julia, 158 bytes
I'm sure this could be shorter with a more clever approach, but this is what I have for now.
(s,g)->(j=0;p=cell(5,1);for i=[604800,86400,3600,60,1] p[j+=1],s=s÷i,s%i end;z=findfirst(p);z>0?join([string(p[i],"wdhms"[i])for i=z:min(z+g-1,5)]," "):"0s")

This creates an unnamed function that accepts two integers as input and returns a string. To call it, give it a name, e.g. f=(s,g)->....
Ungolfed + explanation:
function f(s, g)
    # Initialize an array and an index
    p = cell(5, 1)
    j = 0

    # Loop over the number of seconds in a week, day, hour,
    # minute, and second
    for i in [604800, 86400, 3600, 60, 1]
        # Set the jth element in p to be the quotient and s
        # to be the remainder of i into s
        p[j+=1], s = s ÷ i, s % i
    end

    # Get the index of the first nonzero value in p
    z = findfirst(p)

    if z > 0
        # We start the string at the first nonzero value
        # and continue until we hit the desired number of
        # units (z+g-1) or the maximum number of units (5),
        # whichever comes first. The appropriate unit is
        # appended to each value and the values are then
        # joined with a space.
        join([string(p[i], "wdhms"[i]) for i in z:min(z+g-1,5)], " ")
    else
        # If there are no nonzero values in p, we just
        # have 0 seconds
        "0s"
    end
end

Examples:
julia> f(82815, 6)
"23h 0m 15s"

julia> f(604800, 4)
"1w 0d 0h 0m"

rs, 367 bytes
^(\d+)/(_)^^(\1)
(_*) (\d)/\1!\2
_{60}/#
#{60}/@
@{24}/:
:{7}/;
(_+)/(^^\1)s
(#+)/(^^\1)m
(@+)/(^^\1)h
(:+)/(^^\1)d
(;+)/(^^\1)w
([a-z])/\1
w ((\d+[^\dd])|!)/w 0d \1
d ((\d+[^\dh])|!)/d 0h \1
h ((\d+[^\dm])|!)/h 0m \1
(m|^) ?!/\1 0s!
!(\d+)/!(_)^^(\1)
#
+#(\d+)([a-z]) ?(.*)!(_*)/\1\2 #\3!\4@
#/
(@+)/ (_)^^((^^\1))
!(_+) \1(_*)/!\2
_+ _+/
+\d+[a-z] ?!_/!
 *!/
^$/0s

Live demo and all test cases.
Messy, messy, messy...
Takes about 3-7 seconds to execute the test cases on Chrome for Android. Do not use debug mode, which can freeze your browser in this case because of all the output that would be printed.

What's rs?-----

@Wideshanks I added a link in the title. It's a regex-based language-ish thing I wrote.

Scala, 147 bytes
def p(s:Int,i:Int)=List(s/604800+"w",s/86400%7+"d",s/3600%24+"h",s/60%60+"m",s%60+"s").dropWhile(k=>k.head=='0'&&k.tail!="s").take(i).mkString(" ")

C#, 239 237 170 164 bytes
This is no where near as compact as other solutions, but I can't pose this challenge without having a stab at it myself.
This latest iteration was inspired by ESC's answer.
Indented for clarity:
string G(int s,int n){
    int[]x={s%60,(s/=60)%60,(s/=60)%24,(s/=24)%7,s/7};
    for(s=5;x[--s]==0&s>0;);
    var o="";
    while(n-->0&s>=0)
        o+=" "+x[s]+"smhdw"[s--];
    return o.Trim();
}

source: Stack Exchange

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

sort: votes


text:
Successfully navigating an asteroid field
Introduction
Everyone knows that the possibility of successfully navigating an asteroid field is approximately 3,720 to 1. But despite your warning, Han Solo is still willing to try his luck.
Fearing for your artificial life, you decide to code, in the ship's peculiar dialect (read: your preferred Code Golf language), an asteroid avoidance program that will decide which path to take in an asteroid field ASCII maze.
Input
The Millenium Falcon has an asteroid field mapping program, that gives data similar to this:
|   #####           #########  |
| ######  #          ###   #   |
|   # #  #  #  ####   #        |
@              ##    ####
|#   #   #       ###   ##      |
|##      ##      ####   #  #   |
|####           ##### #   ##   |

Top rows are left of the Falcon, bottom rows are right of the Falcon, and columns represent what is in front of the ship.

Each # is an obstacle.
Each space is empty space that the ship can fly in.
The input is always 7 characters high. This is the asteroid mapping width limit.
The input is always 32 characters long (30 for the field itself and 2 for the start and end limits). This is the asteroid mapping depth limit. Vertical bars | mark the beginning and the end of the mapping.
@ is the Falcon. It is always in the middle row (4th row) and first column in the input.
The space left in the vertical bars on the last column is the place the ship must arrive at. It is always in the middle row (4th row) and last column in the input.

The input can be taken as a multi-line string, an array of strings, from STDIN or a function parameters, or read from a file.
Possible maneuvers
You are pursued by TIE-Fighters, therefore you must always go forward. There are thus three ways the ship can fly at each step:

- Forward
/ Forward and turn left
\ Forward and turn right

For example, these are valid paths:
@---

  --
 /  \ /
@    -

   -
  / \
 /   \
@     \

As you can see, there is always exactly one move per column. The Falcon is a piece of junk, therefore it cannot do violent turns. Which means moves such as /\ or \/ are disallowed. There must be atleast one pure forward - between two opposite turns. On the other hand, turning one way for multiple steps in a row is possible, as seen above.
The Falcon crashes if one move leads the ship to be in a spot where an obstacle is. For example, these moves lead to crashes:
@-#

@
 \
  #

  #
 /
@

Note that this is not a crash:
@-#
  \
   -

Output
You must output the same asteroid field ASCII, with a valid path to the end. The Falcon must be printed at the end spot instead of the start spot.
For example, a valid output for the input example given before would be:
|   #####           #########  |
| ######  #--------  ###   #   |
|   # #  #/ #  ####\  #        |
 ---------      ##  \ #### ----@
|#   #   #       ### \ ## /    |
|##      ##      #### \ #/ #   |
|####           ##### #-- ##   |

Your path only needs to not crash the falcon. It doesn't need to be the shortest path possible.
You can assume that there will always be at least one possible path to the end.
You can output to STDOUT, in a file or any equivalent as long as the asteroid field is printed exactly like they are in this post (e.g. outputting a list of coordinates for the path is not valid).
Test cases

A normal asteroid field
|   #####           #########  |
| ######  #          ###   #   |
|   # #  #  #  ####   #        |
@              ##    ####
|#   #   #       ###   ##      |
|##      ##      ####   #  #   |
|####           ##### #   ##   |

Possible output
|   #####           #########  |
| ######  #--------  ###   #   |
|   # #  #/ #  ####\  #        |
 ---------      ##  \ #### ----@
|#   #   #       ### \ ## /    |
|##      ##      #### \ #/ #   |
|####           ##### #-- ##   |

Hyperregular asteroid field
|# # # # # # # # # # # # # # # |
| # # # # # # # # # # # # # # #|
|# # # # # # # # # # # # # # # |
@ # # # # # # # # # # # # # #
|# # # # # # # # # # # # # # # |
| # # # # # # # # # # # # # # #|
|# # # # # # # # # # # # # # # |

Possible output
|# # # # # # # # # # # # # # # |
| # # # # # # # # # # # # # # #|
|# # # # # # # # # # # # # # # |
 -# #-# #-# #-# #-# #-# #-# #--@
|#\#/#\#/#\#/#\#/#\#/#\#/#\#/# |
| #-# #-# #-# #-# #-# #-# #-# #|
|# # # # # # # # # # # # # # # |

Death star's core
|    #    #    #         #     |
|         #    #    #          |
|    #    #    #    #    #     |
@    #    #    #    #    #
|    #    #         #    #     |
|    #    #    #    #    #     |
|    #         #    #    #     |

Possible output
|    #    #    #   --    #     |
|  ---    #    #  / #\   -     |
| /  #\   #    # /  # \ /#\    |
 -   # \  #    #/   #  - # ----@
|    #  \ # ----    #    #     |
|    #   \#/   #    #    #     |
|    #    -    #    #    #     |

Death star trench
|##############################|
|##############################|
|##############################|
@
|##############################|
|##############################|
|##############################|

Output
|##############################|
|##############################|
|##############################|
 ------------------------------@
|##############################|
|##############################|
|##############################|

Asteroid cave
|### ##########################|
|## # ############### ## ######|
|# ###  ######## ### ## # #####|
@ ###### ###### ### ## ###
|########  ### ### ## #########|
|########## # ### ## ##########|
|###########              #####|

Possible output
|###-##########################|
|##/#\############### ##-######|
|#/###--######## ### ##/#\#####|
 -######\###### ### ##/###-----@
|########--### ### ##/#########|
|##########\# ### ##/##########|
|###########--------      #####|

Scoring
R2D2 is busy swimming in swamps, so you're going to have to program the Falcon's controller by yourself, which is tedious. Therefore the shortest code wins.

@DJMcMayhem: Technically the first line is "Introduction" ;)

I sort of get how it's supposed to look based on the examples, but the encoding of the moves is still somewhat confusing to me. If you look for example at the "hyperregular" example, except for the first/last move, you always move diagonal. Yet it has - in the path at each turn, which is defined as a "forward" move. But the actual moves are always two diagonal-left followed by two diagonal-right.

@RetoKoradi I can understand that it's not all that obvious but the basic idea is that all moves make you travel the width of a character to the right. The path has to look continuous, which is why the previous/next move after right and left turns are one line above/below the previous one.

@apsillers Both are valid, if I understand you correctly your answer should be good

JavaScript (ES6), 186 201
f=([...s])=>(g=(i,l,c=k=" ")=>s[i]!=k&&s[i]!="@"?0:(i-130)?(s[i]=c,([..."/-\\"].some((c,j)=>!((--j&l&&j!=l)||!g(i+33*(l||j)+1,j,c)))||!(s[i]=k))):(s[i]="@",!console.log(s.join(""))))(99)

Runnable snippet:

<textarea cols="33" rows="7" id="t"></textarea>
<button>Solve >>></button>
<button id="1">Normal</button> <button id="2">Hyperregular</button> <button id="3">Death Star core</button> <button id="4">Death Star trench</button> <button id="5">Asteroid cave</button>{

  // not an open space; nip this recursive branch
  if(s[i]!=" "&&s[i]!="@") { return 0; }

  // we made it! the 130th space is (31,3)
  if(i==130) {
      s[i]="@";
      console.log(s.join(""));
      return true;
  }

  // fill in space with move character or a blank
  // (the space is only to blank out the initial `@`)
  s[i] = c || " ";

  // iterate through the 3 options and recursively explore the map
  return ['/','-','\\'].some((c,j)=>{
    --j;
    // if last move was sideways, and this is the opposite move, skip it
    if(l && j && j!=l) { return 0; }

    // recursively call search function on space pointed to by this move or the last move
    return search(i+33*(l||j)+1, j, c);
  })

  // if the `some` call is false (i.e. all options fail for this space)
  // then blank out this space and return false
  || !(s[i]=" ");

}

@vihan1086 Right, I totally missed those spaces when golf-ifying. D: And switching from an array to a split string is an nice change as well. Thanks. :) I've also made a few other changes (making the current move-character a third argument instead of determined within the function, and storing " " in a variable) that brought my score down even lower.

C (complete program), 249 247 235 bytes
This is a complete program reading the input from a file and outputting the result to stdout. The name of the file is passed as a parameter to the program.
char f[7][33];g(i,j,c){return(i<0|i>6|f[i][j]%32?0:j<31?c%45-2?g(i,j+1,c)||g(i+1,j+1,92)||g(i-1,j+1,47):g(i+c/30-2,j+1,c)||g(i+c/30-2,j+1,45):1)?f[i][j]=j?j-31?c:64:32:0;}main(int p,char**v){read(open(v[1],0),f,231);g(3,0,45);puts(f);}

Ungolfed:
/* the field */
char f[7][33];

/* i - row
 * j - col
 * c - movement
 */
g(i,j,c)
{
    return
            /* if we're in bounds and not on an obstacle */
            (i >= 0 & i<7 & f[i][j] % 32 == 0 ?
                    /* if we haven't reached the end */
                    j < 31 ?
                            /* are we going straight ahead? */
                            c%45-2 ?
                                    /* try to go straight */
                                    g(i,j+1,c)
                                    /* try to turn right */
                                    || g(i+1,j+1,92)
                                    /* try to turn left */
                                    || g(i-1,j+1,47)
                            /* turning */
                            :
                                    /* try to keep turning */
                                    g(i+c/30-2,j+1,c)
                                    /* try to go straight */
                                    || g(i+c/30-2,j+1,45)
                    /* done */
                    :1 /* replace this with c==45 to better represent the last move being a turn */
            /* invalid move, fail */
            :0)
            /* add the correct movement to the field */
            ? f[i][j] = j ? j - 31 ? c : 64 : 32
            /* no path, much sads :( */
            :0;
}

main(int p,char*v[])
{
    /* read input file */
    read(open(v[1],0),f,231);

    /* calculate the path */
    g(3,0,45);

    /* print it out */
    puts(f);
}

Output:
$ ./a.out test.inp
|   #####           #########  |
| ######  #          ###   #   |
|   # #  #  #  ####   #      --|
 ------------- ##----####   /  @
|#   #   #    \ /### \ ##  /   |
|##      ##    - #### \ # /#   |
|####           ##### #---##   |

$ ./a.out test2.inp
|# # # # #-# # # # # #-# # # # |
| # # # #/#\# # # # #/#\# # # #|
|# # # #/# #\# # # #/# #\# # # |
 -# # #/# # #\# # #/# # #\# #  @
|#\# #/# # # #\# #/# # # #\# #/|
| #\#/# # # # #\#/# # # # #\#/#|
|# #-# # # # # #-# # # # # #-# |

$ ./a.out test3.inp
|    #    #    #   ------#     |
|    -    #    #  / #    \     |
|   /#\   #    # /  #    #\    |
 --- # \  #    #/   #    # \   @
|    #  \ #    /    #    #  \ /|
|    #   \#   /#    #    #   - |
|    #    ---- #    #    #     |

$ ./a.out test4.inp
|##############################|
|##############################|
|##############################|
 ------------------------------@
|##############################|
|##############################|
|##############################|

$ ./a.out test5.inp
|###-##########################|
|##/#\############### ##-######|
|#/###--######## ### ##/#\#####|
 -######\###### ### ##/###-----@
|########--### ### ##/#########|
|##########\# ### ##/##########|
|###########--------      #####|

Looks like you missed the end point in the first test.

@RetoKoradi It's a - followed by a \, but the \ is covered up by the @. (My program does the same thing.)

@RetoKoradi Earlier iterations of this handled that case better. It's +4 bytes. I noticed apsillers' solution behaved similarly so I opted to save the space.

I see. It doesn't look right to me, but it's up to the OP to decide what is allowed. I saw that they gave some liberty on how the moves are represented. I would have liked to see a clear and unique definition from the start. It looked like a fun problem, but it's not nearly as interesting with the ambiguity.

Common Lisp, 303 bytes
Had lots of fun with this challenge, it's the first codegolf task I did. Basically there's a simple recursive function that tries every viable move until the end position is reached.
Golfed/Minified
(let((s(open "i"))(n nil)(f(make-string 231)))(read-sequence f s)(labels((r(p s u d)(and(< 0 p 224)(find(aref f p)" @")(setf(aref f p)(cond((= 130 p)#\@)((or(unless d(r(- p 32)#\/ t n))(unless u(r(+ p 34)#\\ n t))(r(+ p(cond(u -32)(d 34)(t 1)))#\- n n))s)((return-from r)))))))(r 99 #\- n n)(princ f)))

Reads input from a file i in working directory. I'm pretty sure there's still room for improvement.
Plain code
(defun run-test (file)
  (let ((stream (open file)) ;;should use with-open-file for autoclose..
        (no nil) ;; alias for brevity
        (field (make-string 231)))
    (read-sequence field stream)
    (labels ((doit (pos sym going-up going-down)
               (and
                 (< 0 pos 224)
                 (find (aref field pos) " @")
                 (setf (aref field pos)
                       (cond
                         ((= 130 pos) #\@)
                         ((or
                            (unless going-down (doit (- pos 32) #\/ t no))
                            (unless going-up (doit (+ pos 34) #\\ no t))
                            (doit (+ pos (cond (going-up -32)
                                               (going-down 34)
                                               (t 1)))
                                  #\- no no))
                          sym)
                         ((return-from doit)))))))
      (doit 99 #\- no no)
      (princ field)
      nil)))

Sample output
|   #####       --  #########  |
| ######  #    /  \  ###   # - |
|   # #  #  # /####\  #     / \|
--   -       / ##   \####  /   @
|#\ /#\  #  /    ### \ ## /    |
|##-   \ ##/     #### \ #/ #   |
|####   ---     ##### #-- ##   |

|  --#    #    #   --    #-    |
| /  \    #    #  / #\   / \   |
|/   #\   #    # /  # \ /#  \  |
-    # \  #    #/   #  - #   \ @
|    #  \ # ----    #    #    -|
|    #   \#/   #    #    #     |
|    #    -    #    #    #     |

|# #-# # # # # #-# # # # # #-# |
| #/#\# # # # #/#\# # # # #/#\#|
|#/# #\# # # #/# #\# # # #/# #\|
--# # #\# # #/# # #\# # #/# #  @
|# # # #\# #/# # # #\# #/# # # |
| # # # #\#/# # # # #\#/# # # #|
|# # # # #-# # # # # #-# # # # |

ActionScript 3, 364 bytes
I split this into two functions; one to change the array into an array of arrays, and one recursive one to compute the flight path.
function m(f){for(var i=0;i<f.length;i++){f[i]=f[i].split("");}n(f,0,3,0);return f;}function n(f,x,y,m){var P=f[y][x],X=x+1,A=y-1,B=y,C=y+1,T=true,F=false,E='-';if (y<0||y>6||P=='#'||P=='|')return F;if (x==31){f[y][x]='@';return T;}if(m<0&&y>0){B=A;C=9;E='/';}else if(m>0&&y<6){A=9;B=C;E='\\';}if (n(f,X,B,0)||n(f,X,A,-1)||n(f,X,C,1)){f[y][x]=E;return T;return F;}

Ungolfed version in a program with one sample asteroid field defined:
package
{
    import flash.display.Sprite;

    public class AsteroidNavigator extends Sprite
    {
        var field:Array;
        public function AsteroidNavigator()
        {
            field = [
"|   #####           #########  |",
"| ######  #          ###   #   |",
"|   # #  #  #  ####   #        |",
"@              ##    ####       ",
"|#   #   #       ###   ##      |",
"|##      ##      ####   #  #   |",
"|####           ##### #   ##   |"];
            m(field);
            printField();
        }

        function m(f){
            for(var i=0;i<f.length;i++){
                f[i]=f[i].split("");\
            }
            n(f,0,3,0);
            return f;
        }

        private function n(field,x,y,m) {
            var C = field[y][x];
            if (x > 31 || C == '#' || C == '|') {
                return false;
            }
            if (x == 31 && y == 3) {
                field[y][x] = '@';
                return true;
            }
            if (m == 0) {
                if (n(x+1, y, 0) || ((y>0) && n(x+1, y-1, -1)) || ((y<6) && n(x+1, y+1, 1))) {
                field[y][x] = '-';
                return true;
                }
            } else if ((m<0) && (y>0)) {
                if ((n(x+1, y-1, -1) || n(x+1, y-1, 0))) {
                    field[y][x] = '/';
                    return true;
                }
            } else if ((m>0) && (y<6)) {
                if ((n(x+1, y+1, 1) || n(x+1, y+1, 0))) {
                    field[y][x] = '\\';
                    return true;
                }
            }
            return false;
        }

        private function printField() {
            var sb = "";
            for each (var row:Array in field) {
                sb += row.join("") + "\n";
            }
            trace(sb);
        }
    }
}

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


text:
Shortest Longest Common Subsequence Code
Your task to to solve the SLCSC problem, which consists in finding the shortest possible code to solve the Longest Common Subsequence problem.
A valid solution to the LCS problem for two or more strings S1, … Sn is any string T of maximal length such that the characters of T appear in all Si, in the same order as in T.
Note that T does not have to be a substring of Si.
Example
The strings axbycz and  xaybzc have 8 common subsequences of length 3:
abc abz ayc ayz xbc xbz xyc xyz

Any of these would be a valid solution for the LCS problem.
Details
Write a program or a function that solves the LCS problem, as explained above, abiding the following rules:

The input will consist of two or more strings containing only lowercase letters.
You may read those strings as an array of strings or a single string with a delimiter of your choice.
Your code must output any single one of the possible solutions to the problem, optionally followed by a linefeed or surrounded by quotes.
You may assume that the strings are shorter than 1000 characters and that there are at most 20 strings.
Within these limits, your code should work as expected in theory (given unlimited time and memory).
Your code must complete the combined test cases of the next section in under an hour on my machine (Intel Core i7-3770, 16 GiB RAM).
Approaches that simply iterate over all possible subsequences will not comply with the time limit.
Using built-ins that trivialize this task, such as LongestCommonSequence, is not allowed.

Standard code-golf rules apply.
Test cases
a
ab

Output: a

aaaaxbbbb
bbbbxcccc
ccccxaaaa

Output: x

hxbecqibzpyqhosszypghkdddykjfjcajnwfmtfhqcpavqrtoipocijrmqpgzoufkjkyurczxuhkcpehbhpsuieqgjcepuhbpronmlrcgvipvibhuyqndbjbrrzpqbdegmqgjliclcgahxoouqxqpujsyfwbdthteidvigudsuoznykkzskspjufgkhaxorbrdvgodlb
qnnprxqpnafnhekcxljyysobbpyhynvolgtrntqtjpxpchqwgtkpxxvmwwcohxplsailheuzhkbtayvmxnttycdkbdvryjkfhshulptkuarqwuidrnjsydftsyhuueebnrjvkfvhqmyrclehcwethsqzcyfvyohzskvgttggndmdvdgollryqoswviqurrqhiqrqtyrl

Output: hxbbpyhogntqppcqgkxchpsieuhbncvpuqndbjqmclchqyfttdvgoysuhrrl or any other common subsequence of the same length

riikscwpvsbxrvkpymvbbpmwclizxlhihiubycxmxwviuajdzoonjpkgiuiulbjdpkztsqznhbjhymwzkutmkkkhirryabricvhb
jnrzutfnbqhbaueicsvltalvqoorafnadevojjcsnlftoskhntashydksoheydbeuwlswdzivxnvcrxbgxmquvdnfairsppodznm
kzimnldhqklxyezcuyjaiasaeslicegmnwfavllanoolkhvqkjdvxrsjapqqwnrplcwqginwinktxnkfcuuvoyntrqwwucarfvjg

Output: icsvllvjnlktywuar or any other common subsequence of the same length

rblartqkfggrjpiipuzzypkycnyckkcqceeujiyy
yfpnedyjtiwrhyuktripdwyvgkblzodeufkelhub
ywcyboxwqkibwvredkrbdsyudkulpvmhixeqxynh
bnxwahbzhwjxkotnvbxrojkkldtsodtjmvdrmbgr

Output: krkk or any other common subsequence of the same length

bwfscmotshoczmduwaev
coywaaizdaxjovipsmeh
dobzcpoiedenzlfdjpiu
bbhfeqscvvbwkuoxdoge
drqrzwbcpcsvneodelja

Output: code or any other common subsequence of the same length

nqrualgoedlf
jgqorzglfnpa
fgttvnogldfx
pgostsulyfug
sgnhoyjlnfvr
wdttgkolfkbt

Output: golf or any other common subsequence of the same length

epopyfuhgowedpiqpgfj
ddxyestqynpwmytxhozm
ptubgzyqqksieoovuezv
tovotqmnhgzttfpywjgr
aomvytkgaijlgqzkljls
vzvxpaixrnprxvenbbuo
syfuwxlpcyontqlmfvib
arxleuomstkjegpduwcx
xgqrxaopouvkvwgbzewn
yggunddigctgpnuztzai
izroomywwztdymqszsuo
kiawjnxjncdtufhkrjsp

Output: the empty string

dupe? http://codegolf.stackexchange.com/questions/20427/longest-common-subsequence-of-two-strings-containing-a-particular-substring?rq=1

@NotthatCharles Not all all. That question gives only two strings as input and has no time limit. All existing answers use naïve approaches that are magnitudes too slow to comply with this question's rules.

The last example probably takes the longest time to compute, however by first removing every character which doesn't appear in every string it is trivial to output the empty string. Could you add another example with the same number of strings and length of strings, where every character used appears in every string and where the LCS is at least 5 characters or so? Something like: https://ghostbin.com/paste/x9caq

@Tylio Incorporating some logic that ends recursion early if the strings have no more common characters is pretty much what the last test case is about.

@Dennis So the solution shouldn't be able to run in reasonable time with 20 arbitrary length 1000 strings?

@Tyilo: Unless those strings don't share characters, I don't think it's even possible. I'll post a clarifying edit.

@Dennis, ok my solution now exploits this when possible and it can now handle the last case very fast.

This is slightly tricky: I keep making Pyth segfault!

CJam, 31
q~L{_:&\f{_2$f#:).>j+}{,}$W>s}j

Try it online
9 bytes golfed thanks to Dennis!
Explanation:
This algorithm tries every possible character for the first position of the subsequence, replaces each string with the substring after the first occurrence of that character, and then calls itself recursively (with memoization).
q~          read and evaluate the input (taken as an array)
L{…}j       execute block with recursive memoization and no starting values
  _         duplicate the array of strings
  :&\       intersect the strings as character sets and move before the array
             these are all the possible characters for the sequence
  f{…}      for each character and the array
    _2$     duplicate the array and the character
    f#      find the character position in each string
    :)      increment the positions (to skip the character)
    .>      slice each string starting at the corresponding position
    j       call the j block recursively
    +       concatenate the starting character with the result
  {,}$      sort resulting strings (one for each character) by length
  W>        keep only the last element, if any
  s         convert (from 0/1-string array) to string

Python - 665 644
Indentation levels:
1: space
2: tab
3: tab + space
4: 2 tabs
5: 2 tabs + space

The code defines a function o, which takes a list of strings as arguments and returns one of the LCS's for the strings.
def o(t):
 t=[[y for y in x if y in reduce(lambda x,y:x.intersection(y),t,set(t[0]))]for x in t];l=map(len,t);C=[0]*reduce(lambda x,y:x*-~y,l,1);y=lambda z:[x-1for x in z];m=len(t);e=enumerate
 def g(h):
    r,x=0,1
    for k,j in e(h):r+=-~j*x;x*=-~l[k]
    return r
 def f(h):
    i=len(h)
    if i==m:
     b=g(h);c=t[0][h[0]]
     for k,j in e(h):
         if t[k][j]!=c:break
     else:C[b]=1+C[g(y(h))];return
     r=0
     for k,_ in e(h):a=h[:];a[k]-=1;r=max(r,C[g(a)])
     C[b]=r;return
    for j,_ in e(t[i]):f(h+[j])
 def p(h):
    if min(h)==-1:return''
    v=C[g(h)]
    for k,_ in e(h):
        a=h[:];a[k]-=1
        if v==C[g(a)]:return p(a)
    return p(y(h))+t[0][h[0]]
 f([]);return p(y(l))

Test code:
tests = [
"""
a
ab
""",
"""
aaaaxbbbb
bbbbxcccc
ccccxaaaa
""",
"""
hxbecqibzpyqhosszypghkdddykjfjcajnwfmtfhqcpavqrtoipocijrmqpgzoufkjkyurczxuhkcpehbhpsuieqgjcepuhbpronmlrcgvipvibhuyqndbjbrrzpqbdegmqgjliclcgahxoouqxqpujsyfwbdthteidvigudsuoznykkzskspjufgkhaxorbrdvgodlb
qnnprxqpnafnhekcxljyysobbpyhynvolgtrntqtjpxpchqwgtkpxxvmwwcohxplsailheuzhkbtayvmxnttycdkbdvryjkfhshulptkuarqwuidrnjsydftsyhuueebnrjvkfvhqmyrclehcwethsqzcyfvyohzskvgttggndmdvdgollryqoswviqurrqhiqrqtyrl
""",
"""
riikscwpvsbxrvkpymvbbpmwclizxlhihiubycxmxwviuajdzoonjpkgiuiulbjdpkztsqznhbjhymwzkutmkkkhirryabricvhb
jnrzutfnbqhbaueicsvltalvqoorafnadevojjcsnlftoskhntashydksoheydbeuwlswdzivxnvcrxbgxmquvdnfairsppodznm
kzimnldhqklxyezcuyjaiasaeslicegmnwfavllanoolkhvqkjdvxrsjapqqwnrplcwqginwinktxnkfcuuvoyntrqwwucarfvjg
""",
"""
rblartqkfggrjpiipuzzypkycnyckkcqceeujiyy
yfpnedyjtiwrhyuktripdwyvgkblzodeufkelhub
ywcyboxwqkibwvredkrbdsyudkulpvmhixeqxynh
bnxwahbzhwjxkotnvbxrojkkldtsodtjmvdrmbgr
""",
"""
bwfscmotshoczmduwaev
coywaaizdaxjovipsmeh
dobzcpoiedenzlfdjpiu
bbhfeqscvvbwkuoxdoge
drqrzwbcpcsvneodelja
""",
"""
nqrualgoedlf
jgqorzglfnpa
fgttvnogldfx
pgostsulyfug
sgnhoyjlnfvr
wdttgkolfkbt
""",
"""
epopyfuhgowedpiqpgfj
ddxyestqynpwmytxhozm
ptubgzyqqksieoovuezv
tovotqmnhgzttfpywjgr
aomvytkgaijlgqzkljls
vzvxpaixrnprxvenbbuo
syfuwxlpcyontqlmfvib
arxleuomstkjegpduwcx
xgqrxaopouvkvwgbzewn
yggunddigctgpnuztzai
izroomywwztdymqszsuo
kiawjnxjncdtufhkrjsp
"""
]

for s in tests:
 print o(s.strip().split())

Time it takes to run the tests on my computer:
$ time python 52808-shortest-longest-common-subsequence-code-golfed.py
a
x
hecbpyhogntqtpcqgkxchpsieuhbncvhuqndbjqmclchqyfhtdvgoysuhrrl
icsvllvanlktywuar
krkk
code
golf

        9.03 real         8.99 user         0.03 sys

You should add a byte to get your code to 666 bytes. So metal. \m/

@AlexA. Yeah I also noticed that when counting the bytes as it included a newline on the last line.

There are a few small improvements I see right away that should help. Firstly, anywhere you have a (n+1), you can replace it with -~n to save 2 bytes in each case. Also, anywhere you use map with a lambda, consider using list comprehension instead. For example, map(lambda x:x-1,z) can be shortened by three bytes by changing it to [~-x for x in z].

r,x=r+(j+1)*x,x*(l[k]+1) can be shortened to r+=(j+1)*x;x*=(l[k]+1). Also, you don't need u=... because u is only used in one place. Just substitute that code for the letter u.

@Vioz- and mbomb007 Thanks.

Pyth, 59 58 55 35 bytes
L&@Fb?+yPMbeeb@FeMbeolNmyXJbdP@bdlb

Cut a whopping 20 bytes thanks to @isaacg!
55 byte version:
DCHR?k!&.AH@FH?+Cm<1dHeeHql{medH1h.MlZ.eC++<Hk]<1b>HhkH

Cut off 3 bytes by changing .U@bZ to @F (the fold operator).
58 byte version:
DCHR?k!&.AH.U@bZH?+Cm<1dHeeHql{medH1h.MlZ.eC++<Hk]<1b>HhkH

Cut off a byte by changing the format of a boolean conditional.
59 byte version:
DCHR?k|!.AH!.U@bZH?+Cm<1dHeeHql{medH1h.MlZ.eC++<Hk]<1b>HhkH

This was hard! Python kept segfaulting! Pretty sure it was some kind of bug, but I couldn't get a minimal test case. Oh well.
I based the algorithm off of this one. Which is fine, except that that one is designed for only two strings. I had to tweak it a bit to make it work on more. Then, the last test case was taking too long, so I had to add an additional check to exit the recursion if there are no more common characters.
It's pretty slow, but should take less than an hour (hopefully). I'm testing on my Core i3 with 6 GB of RAM, so your 16-GB Core i7 should blow through this. :)
I also took advantage of Pyth's auto-memoizing functions to make it a bit faster.
EDIT: @Dennis said it passes!
To test it, add the following line:
CQ

and give it a list of strings via standard input (e.g. ['a', 'ab']).
Explanation for the 35 byte version:
WIP.
Explanation for the 55 byte version:
DCH                                                        define a function C that takes a list of strings H
   R                                                       return the following expression
    ?                                                      if
      !&.AH@FH                                             there are no more common letters OR all the strings are empty
     k                                                     return the empty string
              ?          ql{medH1                          else if the last character of every string is equal
               +Cm<1dHeeH                                  return the result of adding the last character to recursion with every item without its last character
                                 h.MlZ.eC++<Hk]<1b>HhkH    otherwise, return the largest result of recursing len(H) times, each time with one element's last character cut off

@Dennis Ok; I'll work on it.

@Dennis Updated. You can try again now.

The last test case finishes instantly now.

@Dennis YESSSSS!!

@kirbyfan64sos About the segfaults: Pyth segfaults when the recursion depth goes too high, such as on infinite recursion.

@isaacg Ahh...that makes sense. It seems to raise the recursion limit to a really high number.

@kirbyfan64sos I golfed your solution down by 20 bytes, to 35 bytes: L&@Fb?+yPMbeeb@FeMbeolNmyXJbdP@bdlb Would you like to incorporate it into your answer, or should I post it separately?

@isaacg I can edit it in, but I'd kind of like to know the changes first... Thanks! :)

Sure. Here are the changes: I removed .AH, which was redundant with @FH. ?k!@FH -> &@FH. <1 -> P. mPd -> PM. med -> eM. ql{eMH1 -> @FeMb. h.MlZ -> eolN. .eC++<Hk]Pb>HhkK -> myXJbdP@bdlb (changed from manual list construction to X, assign-at). DCHR -> L, and changed C to y and H to b. The function you call is now y.

C, 618 564 bytes
d,M,N,A[9999][2];char*(R[9999][20]),b[1000];L(char**s,n){char*j[20],c,a=0;int x[n],y=n-1,z,i,t,m=0,w=1;for(;y;)x[y--]=999;for(;y<N;y++){for(i=0;i<n&&s[i]==R[y][i];i++);if(i/n){a=A[y][0];m=A[y][1];w=0;if(m+d<M||!a)goto J;else{c=a;goto K;}}}for(c=97;w&&c<'{';c++){K:t=1,y=1,z=1;for(i=0;i<n;j[i++]++){for(j[i]=s[i];*j[i]-c;j[i]++)t&=!!*j[i];y&=j[i]-s[i]>x[i]?z=0,1:0;}t&=!y;I:if(t){if(z)for(i=0;i<n;i++)x[i]=j[i]-s[i];d++,t+=L(j,n),d--,m=t>m?a=c,t:m;}}if(w){for(y=0;y<n;y++)R[N][y]=s[y];A[N][0]=a;A[N++][1]=m;}J:if(d+m>=M)M=d+m,b[d]=a;if(!d)N=0,M=0,puts(b);return m;}

And here it is unraveled, for "readability":
d,M,N,A[9999][2];
char*(R[9999][20]),b[1000];
L(char**s,n){
    char*j[20],c,a=0;
    int x[n],y=n-1,z,i,t,m=0,w=1;
    for(;y;)
        x[y--]=999;
    for(;y<N;y++){
        for(i=0;i<n&&s[i]==R[y][i];i++);
        if(i/n){
            a=A[y][0];
            m=A[y][1];
            w=0;
            if(m+d<M||!a)
                goto J;
            else{
                c=a;
                goto K;
            }
        }
    }
    for(c=97;w&&c<'{';c++){
        K:
        t=1,
        y=1,
        z=1;
        for(i=0;i<n;j[i++]++){
            for(j[i]=s[i];*j[i]-c;j[i]++)
                t&=!!*j[i];
            y&=j[i]-s[i]>x[i]?z=0,1:0;
        }
        t&=!y;
        I:
        if(t){
            if(z)
                for(i=0;i<n;i++)
                    x[i]=j[i]-s[i];
            d++,
            t+=L(j,n),
            d--,
            m=t>m?a=c,t:m;
        }
    }
    if(w){
        for(y=0;y<n;y++)R[N][y]=s[y];
        A[N][0]=a;
        A[N++][1]=m;
    }
    J:
    if(d+m>=M)
        M=d+m,b[d]=a;
    if(!d)
        N=0,M=0,puts(b);
    return m;
}

Ladies and gentlemen, I've made a horrible mistake. It used to be prettier... And goto-less... At least now it is fast.
We define a recursive function L that takes as input an array s of arrays of characters and the number n of strings. The function outputs the resulting string to stdout, and incidentally returns the size in characters of that string.
The Approach
Though the code is convoluted, the strategy here is not all too complex. We start with a rather naive recursive algorithm, which I will describe with pseudocode:
Function L (array of strings s, number of strings n), returns length:

Create array of strings j of size n;

For each character c in "a-z",
    For each integer i less than n,
         Set the i'th string of j to the i'th string of s, starting at the first appearance of c in s[i]. (e.g. j[i][0] == c)
         If c does not occur in the i'th string of s, continue on to the next c.
    end For

    new_length := L( j, n ) + 1; // (C) t = new_length
    if new_length > best_length
        best_character := c; // (C) a = best_character
        best_length := new_length; // (C) m = best_length
    end if
end For

// (C) d = current_depth_in_recursion_tree
if best_length + current_depth_in_recursion_tree >= best_found
     prepend best_character to output_string // (C) b = output_string
     // (C) M = best_found, which represents the longest common substring found at any given point in the execution.
     best_found = best_length + current_depth;
end if

if current_depth_in_recursion_tree == 0
    reset all variables, print output_string
end if

return best_length

Now, this algorithm on its own is pretty atrocious (but can be fit in around ~230 bytes, I've found). This is not how one gets speedy results. This algorithm scales incredibly poorly with string length. This algorithm does, however, scale fairly well with larger numbers of strings. The last test case would be solved virtually instantly, since no strings in s have any characters c in common. There were two main tricks I've implemented above that resulted in an incredible speed increase:

At every call to L, check if we've been given this same input before. Since in practice information is passed around via pointers to the same set of strings, we don't actually have to compare strings, just locations, which is great. If we find that we've gotten this information before, there's no need to run through the calculations (most of the time, but getting output makes this a bit more complicated) and we can get away with just returning the length. If we do not find a match, save this set of input/output to compare to future calls. In the C code, the second for loop attempts to find matches to the input. Known input pointers are saved in R, and the corresponding length and character output values are stored in A. This plan had a drastic effect on runtime, especially with longer strings.

Every time we find the locations of c in s, there's a chance we know right off the bat that what we've found isn't optimal. If every location of c appears after some known location of another letter, we automatically know that this c does not lead to an optimal substring, because you can fit one more letter in it. This means that for a small cost, we can potentially remove several hundred calls to L for large strings. In the above C code, y is a flag set if we automatically know that this character leads to a suboptimal string, and z is a flag set if we find a character that has exclusively earlier appearances than any other known character. The current earliest appearances of characters are stored in x. The current implementation of this idea is a bit messy, but nearly doubled performance in many instances.

With these two ideas, what didn't finish in an hour now took about 0.015 seconds.
There are probably plenty more little tricks that can speed up performance, but at this point I started worrying about my ability to golf everything. I'm still not content with the golf, so I'll likely come back to this later!
Timings
Here's some testing code, which I invite you to try online:
#include "stdio.h"
#include "time.h"

#define SIZE_ARRAY(x) (sizeof(x) / sizeof(*x))

int main(int argc, char** argv) {
    /* Our test case */
    char* test7[] = {
        "nqrualgoedlf",
        "jgqorzglfnpa",
        "fgttvnogldfx",
        "pgostsulyfug",
        "sgnhoyjlnfvr",
        "wdttgkolfkbt"
    };

    printf("Test 7:\n\t");
    clock_t start = clock();

    /* The call to L */
    int size = L(test7, SIZE_ARRAY(test7));

    double dt = ((double)(clock() - start)) / CLOCKS_PER_SEC;
    printf("\tSize: %d\n", size);
    printf("\tElapsed time: %lf s\n", dt);

    return 0;
}

I ran the OP's test cases on a laptop equipped with a 1.7 GHz Intel Core i7 chip, with an optimization setting of -Ofast. The simulation reported a peak of 712KB required.  Here's an example run of each test case, with timings:
Test 1:
    a
    Size: 1
    Elapsed time: 0.000020 s
Test 2:
    x
    Size: 1
    Elapsed time: 0.000017 s
Test 3:
    hecbpyhogntqppcqgkxchpsieuhbmcbhuqdjbrqmclchqyfhtdvdoysuhrrl
    Size: 60
    Elapsed time: 0.054547 s
Test 4:
    ihicvaoodsnktkrar
    Size: 17
    Elapsed time: 0.007459 s
Test 5:
    krkk
    Size: 4
    Elapsed time: 0.000051 s
Test 6:
    code
    Size: 4
    Elapsed time: 0.000045 s
Test 7:
    golf
    Size: 4
    Elapsed time: 0.000040 s
Test 8:

    Size: 0
    Elapsed time: 0.000029 s

Total time: 0.062293 s

In golfing, I hit performance rather significantly, and since people seemed to like the brute speed (0.013624 s to complete all test cases combined) of my previous 618-byte solution, I'll leave it here for reference:
d,M,N,A[9999][2];char*(R[9999][20]),b[1000];L(char**s,n){char*j[20],c,a=0;int x[n],y,z,i,t,m=0,w=1;for(y=0;y<n;y++)x[y]=999;for(y=0;y<N;y++){for(i=0;i<n;i++)if(s[i]!=R[y][i])break;if(i==n){a=A[y][0];m=A[y][1];w=0;if(m+d<M||!a)goto J;else{c=a;goto K;}}}for(c=97;w&&c<'{';c++){K:t=1,y=1,z=1;for(i=0;i<n;j[i++]++){for(j[i]=s[i];*j[i]-c;j[i]++)if(!*j[i]){t=0;goto I;}if(j[i]-s[i]>x[i])z=0;if(j[i]-s[i]<x[i])y=0;}if(y){t=0;}I:if(t){if(z){for(i=0;i<n;i++){x[i]=j[i]-s[i];}}d++,t+=L(j,n),d--,m=t>m?(a=c),t:m;}}if(w){for(y=0;y<n;y++)R[N][y]=s[y];A[N][0]=a;A[N++][1]=m;}J:if(d+m>=M)M=d+m,b[d]=a;if(!d)N=0,M=0,puts(b);return m;}

The algorithm itself is unchanged, but the new code relies on divisions and some trickier bitwise operations that end up slowing the whole thing down.

I was thinking about posting a fastest-code challenge about a similar topic, but it looks like I don't have to anymore. 0.01s and 712KB is just astonishing.

This is simply amazing!

Looking over your explanation, what the heck is best_found? It's only mentioned twice, once when it's used in the conditional, and the other when it's reset.

Looking over the C source, it seems that best_found is set to best_length + current_depth. You should probably mention that in the explanation!

@kirbyfan64sos best_found is a global integer that describes the length of the longest common substring found at any given point in execution. I'll put that in the explanation!

Python 2, 285
Code:
import re
def f(s,a,b):
  if b==[]:return s+f('',[],a)
  if a==[]:return s+max([f(b[0][i],[b[0][i+1:]],b[1:]) for i in range(len(b[0]))],key=len) if b[0]!='' else ''
  return max([f(s,a+[b[0][i.start()+1:]],b[1:]) for i in re.finditer(s[-1],b[0])],key=len) if ~b[0].find(s[-1]) else ''

Usage:
print f('',[],['axbycz','xaybzc'])

Explanation:
This is a recursive function. s is the character we are looking for. a contains list of strings sliced after s. b contains list of strings untouced yet. f returns the longest common string.
The first condition checks if we finished to go through all the strings. if so, it means s is common character, and it returns s and looking for more common characters.
The second condition checks if we don't start to go through any string, meaning we don't even have a character (a==[] is equivalent to s==''). if so we check each character of the first string in b.
The last line moves the first string in b to a, by finding each occurrence of s in this string.
On the first call, s should be empty string. a should be empty list and b should contains all the strings.

You should use default arguments so that only the strings need to be supplied to the function, like f(b,s='',a=[]).


text:
40 Numbers in 9 Bytes
There are 40 ways a directed Hamiltonian path can be arranged on a 3×3 grid:

This graphic (thanks Sp3000!) shows only the 20 undirected paths. Traverse each colored line in both directions for the 40 directed paths.
Challenge
Using only printable ASCII, write a 3×3 grid of characters, such as:
ABC
DEF
GHI

When each of the 40 directed paths are read from this grid as 40 single-line, 9-character programs, the goal is to have each program output a unique integer from 1 to 40. Doing this for all 40 paths seems difficult and unlikely, so you only need to make it work for as many paths as you can.
The submission whose 40 path-programs output the most distinct numbers from 1 to 40 will be the winner. Tiebreaker goes to the earlier submission.
Path-programs that error or do not output an integer from 1 to 40 or output an integer that another path-program already covered are not counted. Specifically:

Programs that error while compiling, running, or exiting are not counted. Warnings are ok.
Programs that don't output an integer from 1 to 40 or output something slightly malformed such as -35 or 35 36 are not counted.
Programs that require user input to produce the output are not counted.
Programs that never end are not counted.
From now on, programs that aren't deterministic aren't counted.
Otherwise valid programs that output an integer from 1 to 40 that another valid program has already output are not counted. (The first program is counted.)
Only programs that output integer representations of numbers from 1 to 40 (inclusive) are counted towards your total. The numbers are expected to be in the usual 1, 2, ..., 39, 40 format, unless that is not the norm for your language. (A trailing newline in the output is fine.)
Which numbers your programs output and what order they are in does not matter. Only the number of distinct integers from valid programs matters.

All path-programs must be run in the same language. However, the "programs" may in fact be functions (with no required arguments) or REPL commands, as well as full programs, that print or return their target integer. You may mix and match between functions, REPL commands, and full programs.
Your 9 printable ASCII characters do not need to be distinct.
Example
If your 3×3 grid were
ABC
DEF
GHI

and your 40 programs and outputs looked like this
ABCFEDGHI -> 26
ABCFIHEDG -> 90
ABCFIHGDE -> 2
ABEDGHIFC -> syntax error
ADEBCFIHG -> prints 40 but then errors
ADGHEBCFI -> 6
ADGHIFCBE -> 6
ADGHIFEBC -> 6
CBADEFIHG -> runtime error
CBADGHEFI -> 3
CBADGHIFE -> 4
CFEBADGHI -> -32
CFIHEBADG -> 38.0
CFIHGDABE -> "36"
EDABCFIHG -> 33
EFCBADGHI -> no output
EHGDABCFI -> compilation error
EHIFCBADG -> 8
GDABCFEHI -> 22
GHEDABCFI -> 41
IHGDEFCBA -> 0
GDEHIFCBA -> '9'
EDGHIFCBA -> +10
CFIHGDEBA -> 11
GHIFCBEDA -> error
IFCBEHGDA -> error
EBCFIHGDA -> prints 23 but then loops infinitely
CBEFIHGDA -> randomly prints either 24 or 44
GHIFEDABC -> error
IFEHGDABC -> 30
EFIHGDABC -> 39
IHGDABEFC -> 7
GDABEHIFC -> 29
EBADGHIFC -> -1
GHIFCBADE -> 26
IHGDABCFE -> 1
IFCBADGHE -> error
GDABCFIHE -> no output
IHEFCBADG -> no output
IFCBADEHG -> "quack"

your score would be 14, because there are 14 distinct integers from 1 to 40 validly output, namely 26 2 6 3 4 33 8 22 11 30 39 7 29 1.

-1, challenge contains no reference to flags

@Sp3000 Is the arrangement in the image in a particular order? (I assume for the challenge the ordering isn't important, but I'm dying of curiosity about the image. Particularly, if these were used as seeds in an L-System for a Hilbert Space Curve, is there a natural encoding for the set?)

@luserdroog Well, Sp made the image, best to ask him.

@luserdroog If you number the cells 1 to 9, they should be in lexicographical order, e.g. the first is 123654789

@luserdroog (That is, choose the lexicographically-earlier representative of each pair of directed paths, and then sort those 20 representatives lexicographically.)

PARI/GP - 24
1%1
 8
2+3

PARI/GP ignores spaces between digits, so that 1 8 2, for example is treated as 182. The same could work for perl by replacing the spaces with underscores. I haven't exhausted the entire search space, so there may be better candidates.
A program can be fed to gp as gp -q -f program.gp, or interactively in the repl.

Output
1%1 8 2+3 -> 4
1%1 3+8 2 -> 83 # invalid
1%1 3+2 8 -> 29
1%8 2+3 1 -> 32
1 8%1 3+2 -> 7
1 2+8%1 3 -> 20
1 2+3 1%8 -> 19
1 2+3 8%1 -> 12
1%1 8 3+2 -> 3
1%1 2+8 3 -> 84 # invalid
1%1 2+3 8 -> 39
1 8%1 2+3 -> 9
1 3+8%1 2 -> 21
1 3+2 1%8 -> 18
8 1%1 3+2 -> 5
8 1%1 2+3 -> 12 # dup
8+2 1%1 3 -> 16
8+3 1%1 2 -> 15
2 1%1 8+3 -> 6
2+8 1%1 3 -> 5  # dup
3+2 8 1%1 -> 3  # dup
2 8+3 1%1 -> 28
8 2+3 1%1 -> 82 # invalid
1 3+2 8%1 -> 13
2+3 1%8 1 -> 33
3 1%8+2 1 -> 28 # dup
8%1 3+2 1 -> 29 # dup
1%8 3+2 1 -> 22
2+3 8 1%1 -> 2
3 8+2 1%1 -> 38
8 3+2 1%1 -> 83 # invalid
3+2 1%8 1 -> 24
2 1%8+3 1 -> 36
8%1 2+3 1 -> 39 # dup
2+3 1%1 8 -> 15 # dup
3+2 1%1 8 -> 6  # dup
3 1%1 2+8 -> 15 # dup
2 1%1 3+8 -> 16 # dup
3+8 1%1 2 -> 12 # dup
3 1%1 8+2 -> 15 # dup

All but 4 values are within the required range, with 12 duplicate entries.

Update
I've finished crunching, there are six distinct 23s, and only one 24 (as read by rows):
23 1%1 6 2+3 [2, 3, 4, 5, 7, 8, 11, 12, 13, 14, 16, 17, 18, 19, 22, 24, 26, 27, 32, 33, 34, 36, 37]
23 1 2%3+2*8 [2, 5, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 22, 23, 25, 26, 29, 31, 32, 37, 40]
23 2 3%1+8 2 [2, 4, 6, 7, 10, 11, 12, 13, 14, 15, 16, 20, 21, 23, 24, 28, 29, 30, 31, 32, 33, 34, 40]
23 4%6%5*7+6 [2, 4, 5, 6, 7, 8, 9, 12, 13, 19, 21, 23, 24, 26, 29, 31, 32, 33, 34, 37, 38, 39, 40]
23 5%6%4*7+6 [2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 25, 26, 29, 31, 33, 34, 37, 38, 39, 40]
23 5%6%4*8+6 [1, 3, 5, 6, 8, 9, 10, 12, 14, 15, 18, 22, 24, 25, 27, 29, 30, 32, 34, 36, 37, 39, 40]

24 1%1 8 2+3 [2, 3, 4, 5, 6, 7, 9, 12, 13, 15, 16, 18, 19, 20, 21, 22, 24, 28, 29, 32, 33, 36, 38, 39]

The program I used for crunching is below. PARI/GP has limited string processing capabilities, so deal mainly with char arrays (a.k.a. Vecsmall). The operators tested are +, -, *, \ (floor div), %, ; (expression separator, essentially discards everything before it), and  (space, as described above). The exponent operator ^ could also be added, but it becomes too slow to test exhaustively.
perms = {[
  [1, 2, 3, 6, 5, 4, 7, 8, 9], [1, 2, 3, 6, 9, 8, 5, 4, 7], [1, 2, 3, 6, 9, 8, 7, 4, 5], [1, 2, 5, 4, 7, 8, 9, 6, 3],
  [1, 4, 5, 2, 3, 6, 9, 8, 7], [1, 4, 7, 8, 5, 2, 3, 6, 9], [1, 4, 7, 8, 9, 6, 3, 2, 5], [1, 4, 7, 8, 9, 6, 5, 2, 3],
  [3, 2, 1, 4, 5, 6, 9, 8, 7], [3, 2, 1, 4, 7, 8, 5, 6, 9], [3, 2, 1, 4, 7, 8, 9, 6, 5], [3, 6, 5, 2, 1, 4, 7, 8, 9],
  [3, 6, 9, 8, 5, 2, 1, 4, 7], [3, 6, 9, 8, 7, 4, 1, 2, 5], [5, 4, 1, 2, 3, 6, 9, 8, 7], [5, 6, 3, 2, 1, 4, 7, 8, 9],
  [5, 8, 7, 4, 1, 2, 3, 6, 9], [5, 8, 9, 6, 3, 2, 1, 4, 7], [7, 4, 1, 2, 3, 6, 5, 8, 9], [7, 8, 5, 4, 1, 2, 3, 6, 9],
  [9, 8, 7, 4, 5, 6, 3, 2, 1], [7, 4, 5, 8, 9, 6, 3, 2, 1], [5, 4, 7, 8, 9, 6, 3, 2, 1], [3, 6, 9, 8, 7, 4, 5, 2, 1],
  [7, 8, 9, 6, 3, 2, 5, 4, 1], [9, 6, 3, 2, 5, 8, 7, 4, 1], [5, 2, 3, 6, 9, 8, 7, 4, 1], [3, 2, 5, 6, 9, 8, 7, 4, 1],
  [7, 8, 9, 6, 5, 4, 1, 2, 3], [9, 6, 5, 8, 7, 4, 1, 2, 3], [5, 6, 9, 8, 7, 4, 1, 2, 3], [9, 8, 7, 4, 1, 2, 5, 6, 3],
  [7, 4, 1, 2, 5, 8, 9, 6, 3], [5, 2, 1, 4, 7, 8, 9, 6, 3], [7, 8, 9, 6, 3, 2, 1, 4, 5], [9, 8, 7, 4, 1, 2, 3, 6, 5],
  [9, 6, 3, 2, 1, 4, 7, 8, 5], [7, 4, 1, 2, 3, 6, 9, 8, 5], [9, 8, 5, 6, 3, 2, 1, 4, 7], [9, 6, 3, 2, 1, 4, 5, 8, 7]
]}

ops = Vecsmall("+-*\\%; ")

ms = 1

for(c = 48, 57, {
 for(d = c, 57,
  for(f = d, 57,
   for(g = c, 57,
    for(e = 48, 57,
     print1(Strchr([c,d,e,f,g,13]));
     for(h = 1, #ops,
      for(i = 1, #ops,
       for(j = 1, #ops,
        for(k = 1, #ops,
         a = Vecsmall([c, ops[h], d, ops[i], e, ops[j], f, ops[k], g]);
         s = Set();
         for(m = 1, #perms,
          v = Strchr(vecextract(a, perms[m]));
          iferr(b = eval(v), E, b = 0);
          if(b >= 1 && b <= 40, s = setunion(s, [b]))
         );
         if(#s >= ms, ms = min(23, #s); print(#s, " ", Strchr(a), " ", s));
        )
       )
      )
     )
    )
   )
  )
 )
})

Alas, a Perl program doesn't output its last value. A Perl subroutine does, but a subroutine has braces. ("The signature is part of a subroutine's body. Normally the body of a subroutine is simply a braced block of code.") So I don't think this is doable in Perl.

Deadfish, 18
This was actually the first language I tried before I considered infix operators. I'm posting it now for the sheer hilarity of the idea that Deadfish could be useful for something.
iii
ios
sii

For those who don't know Deadfish, i is increment, s is square and o is output, with the accumulator starting at 0 (there's also a 4th instruction d for decrement not used here). The fact that we don't have automatic printing and need to use o is a major drawback, but surprisingly Deadfish doesn't do too terribly here, all things considered. It turns out that the optimal placement of the output operator is in the middle.
iiisoisii 9
iiisiiois 11
iiisiisio 122
iioisiisi 2
iioiisiis 2
iisioiisi 5
iisiisiio 38
iisiisoii 36
iiiiosiis 4
iiiisiosi 17
iiiisiiso 324
isoiiisii 1
isiioiiis 3
isiisiiio 12
oiiiisiis 0
osiiiisii 0
oisiiiisi 0
oiisiiiis 0
siiiisoii 16
sioiiiisi 1
iisiosiii 5
sioiisiii 1
oisiisiii 0
isiisioii 10
siisiioii 6
isiioisii 3
oiisiisii 0
iiosiisii 2
siisoiiii 4
isoisiiii 1
osiisiiii 0
iisiiiosi 7
siiioiisi 3
oiiisiisi 0
siisiiiio 8
iisiiiiso 64
isiiiisio 26
siiiisiio 18
iiosiiiis 2
isiiiiois 5

Python REPL and many more, 22 23
6+7
*5%
6%4

Key observation: If you colour the grid like a checkerboard, the path alternates grid colours as it goes and starts and ends on the same colour.
Still brute forcing for better. Trying with +*% (and even ** for languages where ^ is exponentiation) didn't turn up anything better, unfortunately. I also tried throwing in bitwise operators and only ^ (xor) seemed to mildly help, but the search was taking too long so I've given up.
6+7%5*6%4 6
6+7%4%5*6 24
6+7%4%6*5 21
6+5*6%4%7 8
6*5+7%4%6 33
6*6%5+7%4 4
6*6%4%7+5 5
6*6%4%5+7 7
7+6*5%4%6 9
7+6*6%5%4 8
7+6*6%4%5 7
7%5+6*6%4 2
7%4%5+6*6 39
7%4%6*6+5 23
5*6+7%4%6 33
5%7+6*6%4 5
5%6*6+7%4 33
5%4%7+6*6 37
6*6+7%5%4 38
6%5*6+7%4 9
4%6*5%7+6 12
6*5%4%7+6 8
5*6%4%7+6 8
7%4%6*5+6 21
6%4%7+5*6 32
4%7+5%6*6 34
5+7%4%6*6 23
7+5%4%6*6 13
6%4%5*6+7 19
4%5%6*6+7 31
5%4%6*6+7 13
4%6*6+5%7 29
6*6+5%4%7 37
5+6*6%4%7 5
6%4%7+6*5 32
4%6*6+7%5 26
4%7+6*6%5 5
6*6+7%4%5 39
4%5%7+6*6 40
4%7+6*5%6 4

Next task: Write a program that generates the program with the most unique values. Then golf that program. :)

@RetoKoradi The first part's what I did. The second... later :P

@Sp3000 I finished the brute forcing of this style of solution. There's 6+7*5%6%4, 6+7*4%6%5 and 6+8*4%6%5 (left to right, top to bottom), and nothing else.

@isaacg there are more 23-point solutions if you throw in some more operators, like &|^

Just a random thought: Have you tried allowing + and - in the corners/center? Since they are unary as well as binary operators, that should still result in all valid expressions. Unlikely that it will result in a better solution, but at least it expands the search space. Hmm, actually, it might be a problem because you could end up with sequences of operators.

+/- in the corners, another operator in the middle, and 4 digits. very small search space, easy to brute force. not a horrible idea, but unlikely to beat 23.

J, 15
2 + 1
* 3 *
2 + 3

This outputs only valid numbers, but a lot are duplicates. The unique values are 17 11 16 28 31 23 13 10 21 33 18 24 22 29 27. You can definitely do better by changing operators and the integers involved.
2+1*3*2+3 -> 17
2+1*3+3*2 -> 11
2+1*3+2*3 -> 11
2+3*2+3*1 -> 17
2*3+1*3+2 -> 16
2*2+3+1*3 -> 16
2*2+3*1+3 -> 28
2*2+3*3+1 -> 28
1+2*3*3+2 -> 31
1+2*2+3*3 -> 23
1+2*2+3*3 -> 23
1*3+2*2+3 -> 13
1*3+3+2*2 -> 10
1*3+2*2+3 -> 13
3*2+1*3+2 -> 21
3*1+2*2+3 -> 33
3+2*2+1*3 -> 13
3+3*1+2*2 -> 18
2*2+1*3+3 -> 16
2+3*2+1*3 -> 17
3+2*3*1+2 -> 21
2*3+3*1+2 -> 24
3*2+3*1+2 -> 33
1*3+2*3+2 -> 13
2+3*1+3*2 -> 23
3*1+3+2*2 -> 24
3+1*3+2*2 -> 10
1+3*3+2*2 -> 22
2+3*3*2+1 -> 29
3*3+2*2+1 -> 27
3*3+2*2+1 -> 27
3+2*2+3*1 -> 13
2*2+3+3*1 -> 16
3+2*2+3*1 -> 13
2+3*1+2*3 -> 23
3+2*2+1*3 -> 13
3*1+2*2+3 -> 33
2*2+1*3+3 -> 16
3+3*1+2*2 -> 18
3*1+2*3+2 -> 33

By the way, congrats on hitting 1k rep! :)

@AlexA. Hitting 1k on a J answer, after nothing but Prolog answers. Unfaithful...

It's okay, I'm sure Prolog will understand.

@AlexA. Yes .

@JanDvorak Are you speaking on behalf of Prolog?

><>, 36*
If you're lucky enough!
x;x
lxl
xnx

Since the challenge does not require the code to be deterministic we only have to prove that it is possible (even if improbable) to return 36 numbers and we are done. It was good while it lasted I guess.
(For those not familiar with ><>, a great intro on can be found here)

><> is a stack-based 2D language. This means that instructions aren't executed linearly like most traditional languages — program flow can be up, down, left or right!

I decided to use the "x" instruction in ><>, which changes the instruction pointers direction to either up, down, left or right at random. Since our code will only be one line, that means that we can only look at the cases when it goes right or left, since if the pointer goes up or down, it will just hit the "x" instruction again.
The "n" instruction pops the number at the top of the stack and prints it. However if the stack is empty and there is nothing to pop, an error is raised.
The "l" instruction  simply pushes the length of the stack onto the stack (and lucky for us it does not send an error if the stack is empty), so for example if the stack were empty and "l" would be called, it would push 0 onto the stack. If we would now again call "l", then since the stack has one element (0), it would push 1 to the top of the stack and now that would mean that there would be two things on the stack and that would mean that if we were to call "l" again, we would push 2 onto the stack etc. So we can use "l" to push an arbitrary number onto the stack via the method shown earlier.
The ";" instruction ends the program.
The idea with using "x" is that, for example if there was only one "x" in the code (where A,B,C,D are some instructions):
ABCx;D

The program would execute A then B then C, and upon reaching "x" we would have two possibilites: the code either continues to go right and hits the ";" and exits or it goes left and executes C then B then A then D and only then exits.
So if our code contained one "x", the program gains two possible program flows from which we may choose the most suited program.
I there are two or more "x"es then we gain an infinite number of possible program flows.
Our code has five "x"es, futhermore each of them is in a "starting cell" of the Hamiltonian paths, which means every single program will start with an "x", and every program will have the structure:
xAxBxCxDx

Where A, B, C, D belong to { ; , n, l, l}
This means that there are only 12 unique programs. Furthermore since we always start on an "x", we may look at the case when the program goes left, thus symmetric programs can also be regarded the same.
Up to symmetry there are only 6 different posible programs.
Only 4 of them occur in the programs generated as hamiltonian paths:
xnxlxlx;x
xlxnxlx;x
xnxlx;xlx
xlxnx;xlx

Let us look at the first program "xnxlxlx;x" if we go right at the first step we hit the print command which will raise an error since we have nothing on the stack. If we go left we hit the end program command. So we cannot output any number from these programs.
The second program, "xlxnxlx;x", is a lot more hopeful, since upon going right at the begining a zero is put on the stack, if we then go left at the next "x", our stack gains a one, then going right again we have a 2 that we can then print and continue going right to end the program. We can observe that we can actually print any even number, since in the "xlx" part at the beginning we can reach a number of arbitrary size by going right then left then right again a certain number of times.
Similiarly it can be seen that the third program xnxlx;xlx can output any odd number, by going left at the beginning and then repeating the "xlx" routine only this time going left then right then left.
And the fourth program is essentially the same as the second program and can output any even number.
So for the required programs we have:
x;xlxlxnx (none)
x;xlxnxlx (any even number)
x;xlxnxlx (any even number)
x;xlxnxlx (any even number)
xlx;xlxnx (any odd number)
xlxnx;xlx (any even number)
xlxnxlx;x (any even number)
xlxnxlx;x (any even number)
x;xlxlxnx (none)
x;xlxnxlx (any even number)
x;xlxnxlx (any even number)
xlx;xlxnx (any odd number)
xlxnx;xlx (any even number)
xlxnxlx;x (any even number)
xlx;xlxnx (any odd number)
xlx;xlxnx (any odd number)
xnxlx;xlx (any odd number)
xnxlx;xlx (any odd number)
xlx;xlxnx (any odd number)
xnxlx;xlx (any odd number)
xnxlxlx;x (none)
xlxnxlx;x (any even number)
xlxnxlx;x (any even number)
xlxnxlx;x (any even number)
xnxlx;xlx (any odd number)
xlx;xnxlx (any even number)
x;xlxnxlx (any even number)
x;xlxnxlx (any even number)
xnxlxlx;x (none)
xlxnxlx;x (any even number)
xlxnxlx;x (any even number)
xnxlx;xlx (any odd number)
xlx;xnxlx (any even number)
x;xlxnxlx (any even number)
xnxlx;xlx (any odd number)
xnxlx;xlx (any odd number)
xlx;xlxnx (any odd number)
xlx;xlxnx (any odd number)
xnxlx;xlx (any odd number)
xlx;xlxnx (any odd number)

That's 4 programs that cant output numbers, 20 that can output any even number, 16 that can output any odd number. Since there are exactly 20 even numbers and at least 16 odd numbers in the range 1 to 40, then with a certain probability there exists a possibility that there would be 36 different numbers in the range 1 to 40 output by this code block.

36 feels awfully suboptimal for an answer that is effectively loophole abuse

Sometimes i wish fish had one instruction for "print the last thing on stack and exit" that would  a huge help.
I might have a fully optimal loophole answer soon, however

I honestly forgot to add a rule about not counting non-deterministic programs. I've added it now. You're welcome to keep this up because it is clever and well explained, but I won't be accepting this answer.

Sure thing, this answer wasn't intended to be a competing answer anyway, it was more of a knee-jerk reaction when i was reading this challenge and thought of having a fish answer.

GolfScript, 8
192
6#7
281

Currently the highest scoring solution. :P Was nice while it lasted.
Programs
1927#6281 1927
192718#62 192718
19271826# 19271826
19#628172 19
16#927182 16
1628#9271 1628
16281729# 16281729
162817#92 162817
2916#7182 2916
291628#71 291628
29162817# 29162817
27#916281 27
2718#9162 2718
27182619# 27182619
#61927182
#72916281
#82619271
#81729162
261927#81 261927
28#619271 28
1826#7291 1826
26#817291 26
#62817291
271826#91 271826
281729#61 281729
1729#8261 1729
#92718261
29#718261 29
2817#6192 2817
17#826192 17
#71826192
182619#72 182619
2619#8172 2619
#91628172
28172916# 28172916
18261927# 18261927
17291628# 17291628
26192718# 26192718
18#729162 18
172916#82 172916

while it lasted ... for 30 minutes..

Best I could find for GolfScript is 0)1#2#3(4 at 15. Beautiful symmetry too.

@primo: That's clever. I didn't think more comments would actually improve the score.

CJam, 14
3(4
;];
0)1

Below the working programs:
3(4;];0)1 = 11
3(4;1)0;] = 22
3(];0)1;4 = 14
3;0)](4;1 = 11
3;0)1;4(] = 13
3;0)1;](4 = 14
4(3;];1)0 = 20
4(3;0)];1 = 1
4(3;0)1;] = 31
4;1)](3;0 = 20
4;1)0;3(] = 22
0;3(4;])1 = 21
0)];3(4;1 = 21
1)0;];4(3 = 33
4;1)0;](3 = 23
0)1;4(];3 = 3
1;4(])0;3 = 33
4(];1)0;3 = 23
0)1;];3(4 = 24
1)0;3(];4 = 4
0;3(])1;4 = 24
0)1;4(3;] = 13
1)0;3(4;] = 22
1;4(3;0)] = 31
0;3(4;1)] = 22
1)];4(3;0 = 30
1;4(3;])0 = 30

The values generated are:
[1, 3, 4, 11, 13, 14, 20, 21, 22, 23, 24, 30, 31, 33]

Is this code you wrote manually? Or did you systematically enumerate and evaluate code variations? I've been wondering if a language with infix notation might be inherently better for this, or if it's possible to beat @Sp3000's approach with a stack based golfing language.

@Reto I wrote a program that tried all the values 0..9 for the 4 numeric parameters. I also tried to change manually some operators. The problem with a stack based language is that most operators needs 2 parameters on the stack, thus we have lots of errors. Infix languages benefit from the checker structure described by Sp3000 in his post.

Yes, that was exactly my feeling when I saw the basic approach. Having a simple layout that is guaranteed to generate all valid expressions is a big advantage. The only advantage of CJam is that it has a lot more one letter operators.

dc (20)
2+3
*p+
4+5

ABCFEDGHI -> 2+3+p*4+5 -> 5     $ **
ABCFIHEDG -> 2+3+5+p*4 -> 10    $ **
ABCFIHGDE -> 2+3+5+4*p -> 40    $ **
ABEDGHIFC -> 2+p*4+5+3 -> 2     $ **
ADEBCFIHG -> 2*p+3+5+4 -> 2       **
ADGHEBCFI -> 2*4+p+3+5 -> 6     $ **
ADGHIFCBE -> 2*4+5+3+p -> 14    $ **
ADGHIFEBC -> 2*4+5+p+3 -> 11    $ **
CBADEFIHG -> 3+2*p+5+4 -> 6       **
CBADGHEFI -> 3+2*4+p+5 -> 10      **
CBADGHIFE -> 3+2*4+5+p -> 15    $ **
CFEBADGHI -> 3+p+2*4+5 -> 3     $ **
CFIHEBADG -> 3+5+p+2*4 -> 8     $ **
CFIHGDABE -> 3+5+4*2+p -> 34    $ **
EDABCFIHG -> p*2+3+5+4 ->
EFCBADGHI -> p+3+2*4+5 ->
EHGDABCFI -> p+4*2+3+5 ->
EHIFCBADG -> p+5+3+2*4 ->
GDABCFEHI -> 4*2+3+p+5 -> 9     $ **
GHEDABCFI -> 4+p*2+3+5 -> 4     $ **
IHGDEFCBA -> 5+4*p+3+2 -> 20    $ **
GDEHIFCBA -> 4*p+5+3+2 -> 4       **
EDGHIFCBA -> p*4+5+3+2 ->
CFIHGDEBA -> 3+5+4*p+2 -> 32    $ **
GHIFCBEDA -> 4+5+3+p*2 -> 12    $ **
IFCBEHGDA -> 5+3+p+4*2 -> 8       **
EBCFIHGDA -> p+3+5+4*2 ->
CBEFIHGDA -> 3+p+5+4*2 -> 3       **
GHIFEDABC -> 4+5+p*2+3 -> 9       **
IFEHGDABC -> 5+p+4*2+3 -> 5       **
EFIHGDABC -> p+5+4*2+3 ->
IHGDABEFC -> 5+4*2+p+3 -> 22    $ **
GDABEHIFC -> 4*2+p+5+3 -> 6       **
EBADGHIFC -> p+2*4+5+3 ->
GHIFCBADE -> 4+5+3+2*p -> 24    $ **
IHGDABCFE -> 5+4*2+3+p -> 25    $ **
IFCBADGHE -> 5+3+2*4+p -> 20      **
GDABCFIHE -> 4*2+3+5+p -> 14      **
IHEFCBADG -> 5+p+3+2*4 -> 5       **
IFCBADEHG -> 5+3+2*p+4 -> 16    $ **

32 outputs, 20 of them distinct (marked with a $)
2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 14, 15, 16, 20, 22, 24, 25, 32, 34, 40


text:
Javascript function challenge add(1,2) and add(1)(2) both should return 3
A friend of mine challenged me to write a function that works with both of these scenarios
add(1,2)  // 3
add(1)(2) // 3

My instinct was the write an add() function that returns itself but I'm not sure I'm heading in the right direction.  This failed.
function add(num1, num2){
    if (num1 && num2){
        return num1 + num2;
    } else {
        return this;
    }
}

alert(add(1)(2));

So I started reading up on functions that return other functions or return themselves.
http://davidwalsh.name/javascript-functions
https://stackoverflow.com/questions/17235259/javascript-self-calling-function-returns-a-closure-what-is-it-for
https://stackoverflow.com/questions/17235259/javascript-self-calling-function-returns-a-closure-what-is-it-for
I am going to keep trying, but if someone out there has a slick solution, I'd love to see it!

Welcome to PPCG! You tagged this as code-golf, meaning that the shortest possible code will win the contest. If this is your intention, you should remove the code-challenge tag.

I have an answer here on stackoverflow

FYI this is called currying.

JavaScript (as asked)
This is a "correct" way to do it but hardly the golfiest way. It's unclear if you're asking for shortest code (the question looks like it will be closed soon anyway.)
function add(a, b) {
    if(typeof b === "undefined")
        return function(c) { return a + c }
    return a + b
}

Is there any reason not to just use b === undefined here?

JavaScript ES6, 23 bytes
add=(a,b)=>b==+b?a+b:c=>a+c

If you are willing to use ES6, you can use fat-arrow functions and conditionals to write the function.
JavaScript, 55 bytes
function add(a,b){return b==+b?a+b:function(c){return a+c}}

Here's the same function in regular (current version of) JavaScript.
b? will check if b is a non-falsey value
a+b if it is, return the sum of a and b
:c=>a+c if it's not, return a function with a single argument c which returns the sum of c and a

@vihan1086 Still doesn't work for add(1,-1).

add=(a,b)=>b==+b?a+b:c=>a+c.

@Tyilo didn't consider that as a valid input, fixed


text:
The GOLF CPU Golfing Challenge: Sides of a Cuboid
This challenge is the second of a series of fastest-code problems that should be written in the GOLF CPU.  You can find the first here
For this problem, you are given the volume of a cuboid (A rectangular cube).  Each of the side lengths are integers.  You must return the number of distinct cuboids that have that volume.  This sequence matches A034836 (thanks Tylio)
Input:Output [List] [of] [cuboids]
1:1 [1,1,1]
5:1 [1,1,5]
8:3 [1,1,8] [1,2,4] [2,2,2]
24:6 [1,1,24] [1,2,12] [1,3,8] [1,4,6] [2,2,6] [2,3,4]
100:8 [1,1,100] [1,2,50] [1,4,25] [1,5,20] [1,10,10] [2,2,25] [2,5,10] [4,5,5]
1080:52
468719: 1
468720: 678
468721: 2

Your program should be written in GOLF CPU.  For input/output you can either use STDIO or the registers.  Hardcoding primes or answers isn't allowed.
This is a fewest-operations problem, so the answer that solves the examples above with the fewest amount of cycles wins!

Your example for 100 is wrong, it should be 100:8 [1,1,100] [1,2,50] [1,4,25] [1,5,20] [1,10,10] [2,2,25] [2,5,10] [4,5,5].

What are the restrictions on the size of the input?

14,483 cycles
I use the fact that the output depends only on the signature (exponents in the prime factorization) of the input.  I used the formula from https://oeis.org/A034836.  The sieve of Eratosthenes is used to find primes to factorize the input by trial division.
# Input in register n
# Outputs in register r and exit code

# the signature of n (exponents in its prime factorization) are stored in
# memory starting at address 0x1000000000000000.  They are byte-sized
# since the largest exponent we can have is 64 (2**64)

# mov z, 0x1000000000000000 (implicit)
mov y, z

# pull out factors of 2
# number of factors is stored in k
# mov k, 0 (implicit)
factor_two:
  and c, n, 1
  snz c, 3
    shr n, n, 1
    inc k
    jmp factor_two

# store factors of two if nonzero
sz k, 2
  sb z, k
  inc z

# Sieve of Eratosthenes
# we only check odd primes, since we already removed factors of 2
# we store COMPOSITE(i) at address i
# we also check n for divisibility by every prime we find
# note we only have to check for prime factors up to sqrt(n)!

mov i, 1
sieve_loop:
  add i, i, 2 # go to the next odd number
  lb c, i # check if COMPOSITE(i)
  jnz sieve_loop, c # if so, continue

  mulu j, k, i, i # j = i**2
  geu c, j, n              # if i**2 > n:
  jnz end_sieve_loop, c #   break

  # otherwise, i is prime; check if n is divisible by i
  mov k, 0
  factor_i:
    divu q, r, n, i # r = n % i
    snz r, 3
      mov n, q      # n /= i
      inc k
      jmp factor_i

  # store factors of i if nonzero
  sz k, 2
    sb z, k
    inc z

  # now cross off all composites that are odd multiples of i,
  # but only up to sqrt(n)
  shl d, i, 2 # d = 2 * i
  # we already have j = i**2, we can start marking composites here:
  # since every lesser multiple of i must have a smaller  prime factor and
  # therefore must have already been marked

  sieve_inner_loop:
    sb j, 1
    add j, j, d # j += 2*i
    mulu c, k, j, j  # c = j**2
    leu c, c, n             # if j**2 < n:
    jnz sieve_inner_loop, c #   continue

  jmp sieve_loop

end_sieve_loop:

# if n != 1, n is a prime and needs to be added to the signature
cmp c, n, 1
snz c, 2 # skip if n==1
  sb z, 1

#mov z, 0x1000000000000000

# according to https://oeis.org/A034836, we have:
# a(n) = (np + 3*nsq + 2*ntp)/6
# where np = Times@@Binomial[2+s,2],
# ntp = Times@@Floor[Floor[s,3]/s],
# nsq = Times@@(Floor[s/2] + 1),
# and s is the signature

# Binomial[2+s,2] == (1+s)(2+s)/2
# Floor[Floor[s,3]/s] == 1 if s divides 3, 0 otherwise

# I tested this formula up to n=10,000,000

mov t, 0 # <= BUG? (doesn't work without this line)
mov d, 1 # np
mov e, 1 # ntp
mov f, 1 # nsq

product_loop:
  lb s, y
  jz finish, s
  inc y

  divu q, r, s, 3 # r = s % 3
  sz r, 1
    mov e, 0

  inc s
  mulu d, x, d, s # d *= s + 1

  inc s
  mulu d, x, d, s # d *= s + 2
  shr d, d, 1     # d /= 2

  shr s, s, 1     # s /= 2 (s == (s+2)/2 == floor(s/2) + 1)
  mulu f, x, f, s # f *= floor(s/2) + 1

  jmp product_loop

finish:

add r, e, f # r = e + f
shl r, r, 1 # r *= 2
add r, r, f # r += f
add r, r, d # r += d
            # r == d + 3*f + 2*e

divu r, s, r, 6 # r /= 6

halt r

Test cases:
robert@unity:~/golf-cpu$ ./assemble.py cube.golf
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=1
Execution terminated after 42 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=5
Execution terminated after 77 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=8
Execution terminated after 91 cycles with exit code 3.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=24
Execution terminated after 126 cycles with exit code 6.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=100
Execution terminated after 218 cycles with exit code 8.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=1080
Execution terminated after 236 cycles with exit code 52.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=468719
Execution terminated after 9710 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=468720
Execution terminated after 422 cycles with exit code 678.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=468721
Execution terminated after 3561 cycles with exit code 2.
robert@unity:~/golf-cpu$

Total cycles for examples: 29,566,640
It cubes the input number in the algorithm, so the input can't be larger than around 2^21.
Cycle count for example input:
Input    Cycles
1        153
5        75
8        773
24       1,528
100      3,185
1080     27,608
468719   9,676,846
468720   9,764,814
468721   10,091,658

I'm using an algorithm I found on OEIS, which does the following:
cuboids(n):
    if is_prime(n):
        return 1
    res = 0
    for d in divisors(n):
        if d^3 <= n:
            for d0 in divisors(n/d):
                if d0^2 <= n/d:
                    res += 1
                if d0 < d:
                    res -= 1

    return res

This might actually be slower than just trying every divisor combination and checking if d1 <= d2 <= d3, however the bottle-neck is finding the prime anyway.
Divisors are found by using the prime factorization of the number. I'm using the same method to build an array of all primes below the input number as I used in the previous problem.
Run with:
python3 assemble.py 52489-cuboids.golf
python3 golf.py -d 52489-cuboids.bin x=<INPUT>

Output will be in the t register.
Example run:
$ python3 golf.py -d 52489-cuboids.bin x=1080 | grep 'Execution\|t: '
Execution terminated after 27608 cycles with exit code 0. Register file at exit:
t: 52                   0x34

Code:
    call build_primes

    mov q, x
    call is_prime
    jnz prime, a

    shl m, x, 3
    add m, m, 8
    call divisors

    mov y, x
    mov k, l

    mov t, 0

    mov p, m

outer_loop:
    cmp a, p, k
    jnz done, a

    lw d, p

    add p, p, 8

    mulu a, r, d, d
    mulu a, r, a, d
    lequ a, a, y
    jz outer_loop, a

    divu x, r, y, d
    mov m, k
    call divisors

    mov q, m

inner_loop:
    cmp a, q, l
    jnz outer_loop, a

    lw o, q

    add q, q, 8

    mulu a, r, o, o
    lequ a, a, x
    jz skip1, a

    inc t

skip1:
    leu a, o, d
    jz inner_loop, a

    dec t

    jmp inner_loop

done:
    halt 0

prime:
    mov t, 1
    halt 0

# Input: x, m
# Output: l
# x: input number
# m: memory location to store divisors
# l: memory location where last divisor is stored + 8
divisors:
    sw m, 1
    add l, m, 8

    mov p, 2

divisors_outer:
    mov q, 1
    push z, 0

divisors_inner:
    divu y, r, x, p
    jnz divisors_not_divisible, r

    mulu q, r, q, p
    push z, q

    mov x, y

    jmp divisors_inner

divisors_not_divisible:
    mov w, l

divisors_not_divisible_outer:
    mov v, m

    pop t, z
    jz divisors_not_divisible_last, t

divisors_not_divisible_inner:
    cmp a, v, w
    jnz divisors_not_divisible_outer, a

    lw s, v
    mulu a, r, s, t
    sw l, a
    add l, l, 8

    add v, v, 8

    jmp divisors_not_divisible_inner

divisors_not_divisible_last:
    shl i, p, 3
    lw p, i

    cmp a, x, 1
    jz divisors_outer, a

    ret l

# Input: x
# Memory layout: [-1, -1, 3, 5, -1, 7, -1, 11, ...]
# x: max integer
# p: current prime
# y: pointer to last found prime
# i: current integer
build_primes:
    sw 0, -1
    sw 8, -1
    sw 16, 1
    mov y, 16

    mov p, 2

build_primes_outer:
    mulu i, r, p, p
    jnz build_primes_final, r

    geu a, i, x
    jnz build_primes_final, a

build_primes_inner:
    shl m, i, 3
    sw m, -1

    add i, i, p

    geu a, i, x
    jz build_primes_inner, a

build_primes_next:
    inc p
    shl m, p, 3
    lw a, m
    jnz build_primes_next, a

    sw y, p
    mov y, m
    sw y, 1

    jmp build_primes_outer

build_primes_final:
    inc p
    geu a, p, x
    jnz build_primes_ret, a

    shl m, p, 3
    lw a, m
    jnz build_primes_final, a

    sw y, p
    mov y, m
    sw y, 1

    jmp build_primes_final

build_primes_ret:
    ret

# Input: q
# Output: a
is_prime:
    shl m, q, 3
    lw a, m
    neq a, a, -1
    ret a

The cycle counts listed don't add up to the total cycle count you posted.

@NathanMerrill Should be fixed now.


text:
Necklace stones puzzle
Given a necklace with color stones (yellow, white, brown, etc.) of at least two different colors, we describe that necklace using letters that correspond to each color, choosing an arbitrary starting point.
We try to answer these questions:

How many distinct colors does the necklace have?
What's the length of the longest segment of contiguous stones of the same color?
If necklace can be cut at any position, removing all contiguous stones of the same color immediately to the left and to the right of the cutting point, what's the biggest amount of stones which could be taken?

Note that the necklace is considered cyclical. Therefore, letters at the start and end of the given input string can form a single sequence (see second test case below).
Test cases
aaaab -> 2 4 5
aabaa -> 2 4 5
uamaaauumaummuauamumummmmua -> 3 4 5

What's the shortest code to achieve this? Any language is welcome.

Why the arbitrary restriction to these programming languages?

I guess these are good options for shortest code approach

Out of the set of all programming languages, those are probably suboptimal. The questions on this site are actually contests and, unless there's a compelling reason to solve a task in a particular language, restrictions are generally frowned upon by the community.

Feel free to edit my question

I've reworded your question. If any part of my edit conflicts with your original intent, please undo it.

Is the necklace considered cyclical? For example, for aabaa, is the longest segment (question 2) 2 or 4?

Reto,  it's cyclical. It would be 4

Can we assume that there are stones of at least two different colors? If not, how should we interpret question 3?

Right, that's true,  at least  2 colors

Ruby, 90 bytes
-2 bytes thanks to Sʨɠɠan
->a{[(a&a*=2).size,(c=a.slice_when{_1!=_2}.map &:size).max,c.each_cons(2).map(&:sum).max]}

Attempt This Online!

a.uniq => (a&a)

You can save another byte abusing that to eliminate parens later: ->a{[(a&a*=2).size,(c=a.slice_when{_1!=_2}.map &:size).max,c.each_cons(2).map(&:sum).max]}

@Sʨɠɠan Nice work. Thanks!

CJam, 28 bytes
r__&,a\2*e`0f=_2ew::+]::e>S*

Try it online.
How it works
r    e# Read a whitespace-separated token from STDIN.
__   e# Push two copies.
&    e# Intersect two of the copies (removes duplicates).
,a   e# Calculate the length and wrap it in an array.
\    e# Swap the array with the input string.
2*   e# Repeat the input string two times.
e`   e# Perform run-length encoding.
0f=  e# Keep only the repetitions.
_2ew e# Copy and push the overlapping slices of length two.
::+  e# Add the integers in the resulting slices.
]    e# Wrap the entire stack in an array.
::e> e# Compute the maximum of each of the three arrays.
S*   e# Join, separating by spaces.

See the clarification I asked for under the question, after you posted your answer. This does not appear to treat the sequence as cyclical.

I think you might be able to accommodate that new requirement by simply repeating the input string. Add a 2* after the initial r.

@RetoKoradi: Yes, that works. (Were busy editing the question.)

@Dennis I've edited questio removing a missconception on 3rd point.

Well, my initial version is 35 bytes. Not fundamentally very different, but your operator use for slicing and dicing the result of the RLE is more compact.

@diegoaguilar: Right, I misread that. Still, if there are at least two colors, the output will be the same.

Just asking, you repeat the input twice to simmulate the ciclycal necklace, right?

@diegoaguilar: That is correct. Again, this works only because there are at least two colors.

I don't even know which I should go for, both are great!

@diegoaguilar: Since you asked for the shortest possible code (code golf), the Pyth answer is superior to mine. I wouldn't accept an answer before at least a week has passed. Even if nobody is going to beat the Jakube's answer (which may or may not happen), it will give others a chance to participate.

I agree I would also love to see this in not code golf languages though

@diegoaguilar: Another good reason for not accepting an answer too soon. Most users answer in their favorite language, not the shortest possible one. Mine simply happens to be CJam.

Pyth, 20 bytes
l{zeSJhCr+zz8eS+VJtJ

Try it online: Demonstration
Explanation
                      implicit: z = input string
 {z                   set of z
l                     len and print
         +zz          z + z (because cyclic)
        r   8         run-length-encoding
      hC              zip and only use the first column (quantities)
     J                store in J
    S                 sort
   e                  take the maximal element and print
               +V     vectorized add of
                 JtJ  J and J[1:]
             eS       sort and print maximal element

See the clarification I asked for under the question, after you posted your answer. This does not appear to treat the sequence as cyclical.

@RetoKoradi Fixed it.

Haskell, 141 137 bytes
import Data.List
l=length
m=maximum
v#w=l$v$group w
f n=(l$nub n,m$map l$group n,m[last#take i n+head#drop i n|i<-[1..l n-1]])
p n=f$n++n

Usage example:
*Main> map p ["aaaab","aabaa","uamaaauumaummuauamumummmmua"]
[(2,4,5),(2,4,5),(3,4,5)]

How it works: Like the other answers I deal with the cycle by working on the input string concatenated to itself.

distinct colors: length of the list where duplicates are removed
longest segment of the same color: group consecutive colors, get length of each group, take maximum
split and take left and right segments: for each index i: split into left and right part at i, group consecutive colors in each part, add length of the last group of the left part and length of first group of the right part. Take maximum of the sums.

JavaScript (ES6), 203 199 bytes
Credit goes to this answer on Code Review SE for the array unique function.
f=w=>{for(x=Math.max,z=[],o=[[...w+=w].filter((x,p)=>w.search(x)==p).length],i=w.length-(c=1);i;)c=(w[i]!=w[--i]?(z.push(c)&0):c)+1;o.push(x.apply(0,z),x.apply(0,z.map((v,i)=>v+=z[i+1]|0)));return o}

Demo
ES6, so Firefox only for now.

f = w => {
  for (x = Math.max, z = [], o = [
    [...w += w].filter((x, p) => w.search(x) == p).length
  ], i = w.length - (c = 1); i;)
    c = (w[i] != w[--i] ? (z.push(c) & 0) : c) + 1;

  o.push(x.apply(0, z), x.apply(0, z.map((v, i) => v += z[i + 1] | 0)));
  return o
}

// DEMO
console.log = x => document.body.innerHTML += x + "<br>";

console.log(f('aaaab'));
console.log(f('aabaa'));
console.log(f('uamaaauumaummuauamumummmmua'));

Perl 5 -n, 96 bytes
$_.=$_;@k{/./g}++;/(.)\1+(.)\2+/;say for 0+keys%k,length$&,(sort{$b-$a}map y///c,/((.)\2+)/g)[0]

Try it online!
Changed the output order:
Number of unique colors
Longest after cutting
Longest contiguous string of one color

Python 2, 124 bytes
from itertools import*
I=input()*2
r=[len(list(g))for _,g in groupby(I)]
print len(set(I)),max(r),max(map(sum,zip(r,r[1:])))

Try it online!

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