text:
Cycling with Rubik's
While idly twisting my Rubik's cube around, my son noticed that it kept going back to the solved state. I'm pretty sure he thought this was some sort of voodoo magic at first, but I explained that if you keep repeating the same sequence of moves, it will always return to its original state. Eventually.
Of course, being a kid, he had to try it out for himself and picked a "random" sequence he thought would be tricky. He lost track after ten repeats or so, and asked me how many times he would have to repeat it. Not knowing the sequence he was using, I told him I didn't know, but that we could write a program to find out.
This is where you come in. Of course, I could just whip something up, but he'd like to type it in himself. He isn't a very fast typist yet, though, so I need the shortest program possible.
Objective
Given a sequence of turns, output the fewest number of times it must be performed to return the cube to its original state. This is code golf, so least bytes wins. You can write a program or function, and all the other usual defaults apply.
Input
Input is a sequence of moves, taken as a string, list, or other format suitable for your language. Feel free to use a separator (or not) between moves if in string form.
There are six "basic" moves that must be taken into account, along with their inverses:
R - Turn the right face clockwise
L - Turn the left face clockwise
U - Turn the up (top) face clockwise
D - Turn the down (bottom) face clockwise
F - Turn the front face clockwise
B - Turn the back face clockwise

The inverses are represented by adding a prime mark ' after the letter. This indicates you turn that face counterclockwise, so F' turns the front face counterclockwise, and F F' would return it to the original state right away.
For the interested, this challenge is using a limited set of Singmaster Notation. Ruwix has some nice animations if you'd like to see it in action.
Output
Output is simply the minimum number of times the input sequence must be performed.
Examples
Input                Output

FF'               ->      1
R                 ->      4
RUR'U'            ->      6
LLUUFFUURRUU      ->     12
LUFFRDRBF         ->     56
LF                ->    105
UFFR'DBBRL'       ->    120
FRBL              ->    315

Here's a (quite naive) solver to compare your answers to, written in Java. It also accepts 2 for double moves (so the fourth case is equivalent to L2U2F2U2R2U2).
import java.util.ArrayList;
import java.util.List;

public class CycleCounter{

    public static void main(String[] args){
        int[] cube = new int[54];
        for(int i=0;i<54;i++)
            cube[i] = i;

        String test = args.length > 0 ? args[0] : "RUR'U'";
        List<Rotation> steps = parse(test);
        System.out.println(steps.toString());

        int count = 0;
        do{
            for(Rotation step : steps)
                cube = step.getRotated(cube);
            count++;
        }while(!isSorted(cube));

        System.out.println("Cycle length for " + test + " is " + count);
    }

    static List<Rotation> parse(String in){
        List<Rotation> steps = new ArrayList<Rotation>();
        for(char c : in.toUpperCase().toCharArray())
            switch(c){
                case 'R':steps.add(Rotation.R);break;
                case 'L':steps.add(Rotation.L);break;
                case 'U':steps.add(Rotation.U);break;
                case 'D':steps.add(Rotation.D);break;
                case 'F':steps.add(Rotation.F);break;
                case 'B':steps.add(Rotation.B);break;
                case '\'':
                    steps.add(steps.get(steps.size()-1));
                case '2':
                    steps.add(steps.get(steps.size()-1));
                    break;
            }
        return steps;
    }

    static boolean isSorted(int[] in){for(int i=0;i<in.length-1;i++)if(in[i]>in[i+1])return false;return true;}

    enum Rotation{
        R(new int[]{-1,-1,42,-1,-1,39,-1,-1,36, -1,-1,2,-1,-1,5,-1,-1,8, 20,23,26,19,-1,25,18,21,24, -1,-1,11,-1,-1,14,-1,-1,17, 35,-1,-1,32,-1,-1,29,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1}),
        L(new int[]{9,-1,-1,12,-1,-1,15,-1,-1, 27,-1,-1,30,-1,-1,33,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, 44,-1,-1,41,-1,-1,38,-1,-1, -1,-1,6,-1,-1,3,-1,-1,0, 47,50,53,46,-1,52,45,48,51}),
        U(new int[]{2,5,8,1,-1,7,0,3,6, 45,46,47,-1,-1,-1,-1,-1,-1, 9,10,11,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, 18,19,20,-1,-1,-1,-1,-1,-1, 36,37,38,-1,-1,-1,-1,-1,-1}),
        D(new int[]{-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,24,25,26, -1,-1,-1,-1,-1,-1,42,43,44, 29,32,35,28,-1,34,27,30,33, -1,-1,-1,-1,-1,-1,51,52,53, -1,-1,-1,-1,-1,-1,15,16,17}),
        F(new int[]{-1,-1,-1,-1,-1,-1,18,21,24, 11,14,17,10,-1,16,9,12,15, 29,-1,-1,28,-1,-1,27,-1,-1, 47,50,53,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,8,-1,-1,7,-1,-1,6}),
        B(new int[]{51,48,45,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,0,-1,-1,1,-1,-1,2, -1,-1,-1,-1,-1,-1,26,23,20, 38,41,44,37,-1,43,36,39,42, 33,-1,-1,34,-1,-1,35,-1,-1});

        private final int[] moves;
        Rotation(int[] moves){
            this.moves = moves;
        }

        public int[] getRotated(int[] cube){
            int[] newCube = new int[54];
            for(int i=0;i<54;i++)
                if(moves[i]<0)
                    newCube[i] = cube[i];
                else
                    newCube[moves[i]] = cube[i];
            return newCube;
        }
    }
}

"clockwise" means "clockwise when you're facing it" I assume?

@msh210 Correct.

On a point of pedantry, I think you should make it explicit that you want the smallest number which suffices. Otherwise I could just output the size of the group and cite Lagrange's theorem...

@PeterTaylor Pedantry accepted.

I may offer a 500 point bounty for a solution in Shuffle. Not sure yet.

Out of interest, what's the correct answer for LFLF? Although repeating the sequence 105 times returns you to the original state, so does repeating it 52.5 times...

@Neil Assume it's integer output only.

@ThomasKwa I don't think Shuffle is anywhere near Turing complete. I'm pretty sure this is impossible.

So what's the longest a sequence of moves could take? Could that be calculated easily using abstract algebra? Perhaps that's a question for math.SE.

@mbomb007 1260, based on group theory. Not an expert, but maybe reddit can help :)

Pyth, 66 63 bytes
l.uum.rW}Hdd@_sm_B.iFP.>c3Zk3xZHG_r_Xz\'\39Nf!s}RTcZ2y=Z"UDLRFB

Try it online: Demonstration or Test Suite. Notice that the program is kinda slow and the online compiler is not able to compute the answer for RU2D'BD'. But be assured, that it can compute it on my laptop in about 12 seconds.
The program (accidentally) also accepts 2 for double moves.
Full Explanation:
Parse scramble:
First I'll deal with the prime marks ' in the input strings. I simply replace these with 3 and run-length decode this string. Since Pyth's decoding format requires the number in front of the char, I reverse the string beforehand. _r_Xz\'\39. So afterwards I reverse it back.
Describe the solved cube state:
=Z"UDLRFB assigns the string with all 6 moves to Z.
We can describe a cube state by describing the location for each cube piece. For instance we can say that the edge, that should be at UL (Up-Left) is currently at FR (Front-Right). For this I need to generate all pieces of the solved cube: f!s}RTcZ2yZ. yZ generates all possible subsets of "UDLRFB". This obviously also generates the subset "UDLRFB" and the subset "UD". The first one doesn't make any sense, since there is no piece that is visible from all 6 sides, and the second one doesn't make any sense, since there is no edge piece, that is visible from the top and the bottom.
Therefore I remove all the subsets, that contain the subsequence "UD", "LR" or "FB". This gives me the following 27 pieces:
'', 'U', 'D', 'L', 'R', 'F', 'B', 'UL', 'UR', 'UF', 'UB', 'DL', 'DR', 'DF', 'DB',
'LF', 'LB', 'RF', 'RB', 'ULF', 'ULB', 'URF', 'URB', 'DLF', 'DLB', 'DRF', 'DRB'

This also includes the empty string and all the six 1-letter strings. We could interpret them as the piece in the middle of the cube and the 6 center pieces. Obviously they are not required (since they don't move), but I'll keep them.
Doing some moves:
I'll do some string translations to perform a move. To visualize the idea look at the corner piece in URF. What happens to it, when I do an R move? The sticker on the U face moves to the B face, the sticker F moves to the U face and the sticker on the R face stays at the R face. We can say, that the piece at URF moves to the position BRU. This pattern is true for all the pieces on the right side. Every sticker that is on the F face moves to the U face when an R move is performed, every sticker that is on the U face moves to the B face, every sticker on the B moves to D and every sticker on D moves to F. We can decode the changes of an R move as FUBD.
The following code generates all the 6 necessary codes:
_sm_B.iFP.>c3Zk3
['BRFL', 'LFRB', 'DBUF', 'FUBD', 'RDLU', 'ULDR']
    ^       ^       ^       ^       ^       ^
 U move  D move  L move  R move  F move  B move

And we perform a move H to the cube state G as followed:
m.rW}Hdd@...xZHG
m              G   map each piece d in G to:
 .rW   d              perform a rotated translation to d, but only if:
    }Hd                  H appears in d (d is currently on the face H)
            xZH           get the index of H in Z
        @...              and choose the code in the list of 6 (see above)

Count the number of repeats:
The rest is pretty much trivial. I simply perform the input scramble to the solved cube over and over until I reach a position that I previously visited.
l.uu<apply move H to G><parsed scramble>N<solved state>
u...N   performs all moves of the scramble to the state N
.u...   do this until cycle detected, this returns all intermediate states
l       print the length

GAP, 792 783 782 749 650 Bytes
This seems to be working. If it messes up with something let me know.
Thanks to @Lynn for suggesting that I decompose some of the primitive moves.
Thanks to @Neil for suggesting that instead of Inverse(X) I use X^3.
Usage example: f("R");
R:=(3,39,21,48)(6,42,24,51)(9,45,27,54)(10,12,18,16)(13,11,15,17);L:=(1,46,19,37)(4,49,22,40)(7,52,25,43)(30,36,34,28)(29,33,35,31);U:=(1,10,27,28)(2,11,26,29)(3,12,25,30)(37,43,45,39)(40,44,42,38);A:=R*L^3*F*F*B*B*R*L^3;D:=A*U*A;;F:=(1,3,9,7)(2,6,8,4)(10,48,36,43)(13,47,33,44)(16,46,30,45);B:=(27,25,19,21)(26,22,20,24)(39,28,52,18)(38,31,53,15)(37,34,54,12);d:=NewDictionary((),true);AddDictionary(d,'R',R);AddDictionary(d,'L',L);AddDictionary(d,'U',U);AddDictionary(d,'D',D);AddDictionary(d,'F',F);AddDictionary(d,'B',B);f:=function(s) local i,p,b,t;p:=();
for c in s do if c='\'' then t:=t^2;else t:=LookupDictionary(d,c);fi;p:=p*t;od;return Order(p);end;

Here is the ungolfed code with a bit of explanation
  # Here we define the primitive moves
R:=(3,39,21,48)(6,42,24,51)(9,45,27,54)(10,12,18,16)(13,11,15,17);
L:=(1,46,19,37)(4,49,22,40)(7,52,25,43)(30,36,34,28)(29,33,35,31);
U:=(1,10,27,28)(2,11,26,29)(3,12,25,30)(37,43,45,39)(40,44,42,38);
#D:=(7,34,21,16)(8,35,20,17)(9,36,19,18)(48,46,52,54)(47,49,53,51);
F:=(1,3,9,7)(2,6,8,4)(10,48,36,43)(13,47,33,44)(16,46,30,45);
B:=(27,25,19,21)(26,22,20,24)(39,28,52,18)(38,31,53,15)(37,34,54,12);

# Here we define D in terms of other primitive moves, saving on bytes
# Thanks @Lynn
# This is actually doable with a maximum of 3 of the primitive moves
# if a short enough sequence can be found.
D:=U^(R*L^3*F*F*B*B*R*L^3);

# create dictionary and add moves to it with appropriate char labels
d:=NewDictionary((),true);
AddDictionary(d,'R',R);
AddDictionary(d,'L',L);
AddDictionary(d,'U',U);
AddDictionary(d,'D',D);
AddDictionary(d,'F',F);
AddDictionary(d,'B',B);

f:=function(s)
    local c,p,t;

    # p will become the actual permutation passed to the function
    p:=();

    for c in s do
        if c='\'' then
            # The last generator we mutiplied (that we still have in t)
            # should have been its inverse. Compensate by preparing to
            # multiply it two more times to get t^3=t^-1. Thanks @Neil.
            t:=t^2;
        else
            t:=LookupDictionary(d,c);
        fi;
        p:=p*t;
    od;

    return Order(p);

end;

Every move is a fourth root of the identity, so your Inverse is unnecessary.

You can probably replace 45 with 5 in your permutations, and save three bytes.

A result by Benson I found in Singmaster, 1981 says: “Let A = RL⁻¹F²B²RL⁻¹, then AUA = D.” Indeed, A:=R*L*L*L*F*F*B*B*R*L*L*L;D:=A*U*A; is shorter than your definition for D (but I can’t test it...)

Does GAP really not let you write ^-1 for inverses, BTW?

Yeah I totally spaced on using ^-1. Which I assume is pretty much the same thing @Neil was saying, except with ^3 instead (which is actually the shortest). Also, yeah I could decompose moves into other moves, and I should be able to save several bytes by doing so, it would just be a matter of finding the shortest decomposition.

@Lynn I' m not sure I understand what you mean by replacing 45 with 5.

@Liam What Lynn means is that the centre squares never move so you shouldn't number them as that wastes your small numbers (in fact you can save a couple more bytes by starting the numbering from 0).

@Neil ah yeah I see what you're saying. Yeah I probably would be able to, although GAP takes issue if it finds a 0 in a cycle or if I try to declare a permutation with nondisjoint cycles

I dislike if b=true even in ungolfed code. Why not let b be 1 or -1 and do p:=p*t^b? $A$ has order 2, so you can say D:=U^A (and then inline and get rid of $A$). Using a dictionary is clean, but doesn't seem to help getting short code. The function could just end with return Order(p);

@ChristianSievers I'll be honest I've never truly been interested in golfing as such, so I usually just make a nominal effort. You have my permission to make edits though! (If I had more time right now, I would go through it myself)

Okay, I made an edit. I didn't change using a dictionary, and I changed the handling of inverses in a way different from what I suggested. Most of the changes I would do even when not golfing. However, there must be something wrong (already with the old code), as some test cases don't give the expected result. Maybe some primitive moves are not in the correct direction?

@ChristianSievers thanks for doing that. Which cases are failing? I'll take a look hopefully later tonight.

LUFFRDRBF gives 240 but should be 56, UFFR'DBBRL' gives 252 but should be 120 (both from the task description), RUUD'BD' gives 720 but should give 1260 (from the Haskell entry) - instead RUUDBD gives 1260, but only changing D to D' doesn't help in the other cases. - Oh, also changing U and U' works. In the code, only changing this will also fix D. I'll do that.

No, I won't. I thought I could continue editing my version, but I can't. (Why?)

I'm on my phone so I haven't/can't do anything. Do you have enough rep yet? If not,  go to chat and ask someone to approve the edit.

I think I'll just wait for you.

Let us continue this discussion in chat.

My changes are still hidden in the rejected edit you linked to in chat. Maybe you can just copy them from there?

@ChristianSievers I'm really sorry, it completely slipped my mind. Thank you for the reminder. I also still haven't checked the validity cases you mentioned.

No problem. I think my final result was that the definition of U needs to be replaced with its inverse.

Mathematica, 413 401 bytes
Evaluate[f/@Characters@"RFLBUD"]=LetterNumber@"ABFEJNRMDAEHIMQPCDHGLPTOBCGFKOSNADCBILKJEFGHQRST"~ArrayReshape~{6,2,4};
r[c_,l_]:=(b=Permute[c,Cycles@f@l];MapThread[(b[[#,2]]=Mod[b[[#,2]]+{"F","B","L","R"}~Count~l{-1,1,-1,1},#2])&,{f@l,{3,2}}];b);
p@s_:=Length[c={#,0}&~Array~20;NestWhileList[Fold[r,#,Join@@StringCases[s,x_~~t:""|"'":>Table[x,3-2Boole[t==""]]]]&,c,(Length@{##}<2||c!=Last@{##})&,All]]-1

Explanations
A Rubik's Cube is made up with 20 movable cubies (8 corners, 12 edges). Each cubie can be given a number:
corners:
N   starting position
1     UFR
2     UBR
3     UBL
4     UFL
5     DFR
6     DBR
7     DBL
8     DFL

edges:
N   starting position
9     UF
10    UR
11    UB
12    UL
13    FR
14    BR
15    BL
16    FL
17    DF
18    DR
19    DB
20    DL

Note that when the cube is twisted, the cubies are generally not on their starting positions any longer. For example, when R is done, the cubie 1 moves from UFR to a new position UBR.
In such notation, a 90 degree turn can be described by 8 movements of cubies. For example, R is described by
from  to
UFR   UBR
UBR   DBR
DBR   DFR
DFR   UFR
UR    BR
BR    DR
DR    FR
FR    UR

Since each cubie has a unique starting position, each position has a unique starting cubie. That is to say, rule UFR->UBR is just 1->2 (means that R takes the cubie on the starting position of cubie 1 to the starting position of cubie 2). Thus, R can be simplified further to a cycle
Cycles[{{1,2,6,5}, {10,14,18,13}}]

To fully solve a Rubik's Cube, we also need to align the cubies to their corresponding starting orientations. The faces of a cube is painted in different colors, the scheme that I often use when solving cubes is
face color
U    yellow
D    white
F    red
B    orange
R    green
L    blue

When we analyzing the orientations of corners, colors other than yellow or white are ignored, and yellow and white are considered as the same color.
Suppose cubie 1 is on its starting position UFR, the yellow facet may be aligned to three different faces. We use an integer to represent these cases,
0  yellow on U  (correct)
1  yellow on R  (120 degree clockwise)
2  yellow on F  (120 degree counterclockwise)

Suppose cubie 1 is on DFL, its three possible orientations are
0  yellow on D  (correct)
1  yellow on L  (120 degree clockwise)
2  yellow on F  (120 degree counterclockwise)

When we analyzing the orientations of edges, red and orange are ignored, and yellow and white are ignored only if the edge has a green or blue facet.
Suppose cubie 10 is on its starting position UR, the green facet may be aligned to two different faces. Its two possible orientations are
0  green on R  (correct)
1  green on U  (180 degree)

Suppose cubie 10 is on DF, its two possible orientations are
0  green on D  (correct)
1  green on F  (180 degree)

An array is used to store the state of a cube. The starting state of a cube is
{{1,0},{2,0},{3,0},{4,0},{5,0},{6,0},{7,0},{8,0},{9,0},{10,0},{11,0},{12,0},{13,0},{14,0},{15,0},{16,0},{17,0},{18,0},{19,0},{20,0}}

which means that every cubies are on their starting position with correct orientation.
After R, the state of the cube becomes
{{5,2},{1,1},{3,0},{4,0},{6,1},{2,2},{7,0},{8,0},{9,0},{13,1},{11,0},{12,0},{18,1},{10,1},{15,0},{16,0},{17,0},{14,1},{19,0},{20,0}}

which means that cubie 5 is now on position 1 (UFR) with orientation 2, cubie 1 is now on position 2 (UBR) with orientation 1, cubie 3 is now still on position 3 (UBL) with orientation 0, and so on.

Test cases
p["FF'"]            (* 1   *)
p["R"]              (* 4   *)
p["RUR'U'"]         (* 6   *)
p["LLUUFFUURRUU"]   (* 12  *)
p["LUFFRDRBF"]      (* 56  *)
p["LF"]             (* 105 *)
p["UFFR'DBBRL'"]    (* 120 *)
p["FRBL"]           (* 315 *)

Haskell, 252 bytes
r=[-2..2]
s=mapM id[r,r,r]
t m p@[x,y,z]=case m of"R"|x>0->[x,z,-y];"L"|x<0->[x,-z,y];"U"|y>0->[-z,y,x];"D"|y<0->[z,y,-x];"F"|z>0->[y,-x,z];"B"|z<0->[-y,x,z];c:"'"->t[c]$t[c]$t[c]p;_->p
f m=length$s:fst(span(/=s)$tail$iterate(flip(foldl$flip$map.t)m)s)

Sample runs:
*Main> f ["F","F'"]
1
*Main> f ["R"]
4
*Main> f ["R","U","R'","U'"]
6
*Main> f ["L","L","U","U","F","F","U","U","R","R","U","U"]
12
*Main> f ["L","U","F","F","R","D","R","B","F"]
56
*Main> f ["L","F"]
105
*Main> f ["U","F","F","R'","D","B","B","R","L'"]
120
*Main> f ["F","R","B","L"]
315
*Main> f ["R","U","U","D'","B","D'"]  -- maximum possible order
1260

The key observation here is that it’s simpler to model the Rubik’s cube as a 5×5×5 grid of points rather than a 3×3×3 grid of oriented cubies.  Corner cubies become cubes of 2×2×2 points, edge cubies become squares of 2×2×1 points, and moves rotate slices of 5×5×2 points.

This is really clever! I think replacing c:"'" with c:_ saves two bytes.

Thanks! I was looking for a 1260 sequence for the test cases, but couldn't be bothered looking it up :)

@Lynn, that doesn’t work because _ also matches the empty list.

This is great, but it seems very similar to this answer to another question http://codegolf.stackexchange.com/a/44775/15599 . If you were inspired by that you should acknowledge it.

@steveverrill, wow, that does look impressively similar, but no, I hadn’t seen it. My answer is my own independent work. (I acknowledge, of course, that Jan Dvorak came up with most of the same ideas before I did.)

Python 2, 343 bytes
def M(o,v,e):
 k=1
 for m in e:
  for c in'ouf|/[bPcU`Dkqbx-Y:(+=P4cyrh=I;-(:R6'[m::6]:i=~ord(c)%8*k;j=(ord(c)/8-4)*k;o[i],o[j]=o[j]-m/2,o[i]+m/2;v[i],v[j]=v[j],v[i];k=-k
V=range(20)
o,v,e=[0]*20,V[:],[]
for c in raw_input():i='FBRLUD'.find(c);e+=i<0and e[-1:]*2or[i]
M(o,v,e);n=1
while any(o[i]%(2+i/12)for i in V)or v>V:M(o,v,e);n+=1
print n

Input is taken from stdin.
The given sequence of twists is performed repeatedly on a virtual cube until it returns to the solved state. The cube state is stored as an orientation vector and permutation vector, both of length 20.
Orientations are somewhat arbitrarily defined: an edge cubie is oriented correctly if it can be moved into place without invoking an R or L quarter turn. The orientation of the corner cubies is considered relative to the F and B faces.

Sample Usage
$ echo FRBL|python rubiks-cycle.py
315

$ echo RULURFLF|python rubiks-cycle.py
1260

Online Demonstration and Test Suite.

Nice choice of function name and arguments!

Ruby, 225 bytes
->s{n=0
a=[]
b=[]
64.times{|i|a<<j=[(i&48)-16,(i&12)-4,i%4-1];b<<j*1}
d=1
(n+=1
s.reverse.chars{|c|m="UFRDBL".index(c)
m ?(e=m/3*2-1
b.each{|j|j[m%=3]*e>0&&(j[m-2],j[m-1]=j[m-1]*e*d,-j[m-2]*e*d)}
d=1):d=-1})until n>0&&a==b
n}

Similar to Anders Kaseorg's answer and inspired by Jan Dvorak's answer to a previous question.
However unlike those answers, I don't need 125 cubies. I use a rubik's cube of 27 cubies, but rectangular dimensions. In the solved state the corners are at +/-1,+/-4,+/-16.
I generate an array of 64 cubies, each with a centre chosen from x=[-1,0,1,2], y=[-4,0,4,8], z=[-16-0,16,32]. The cubies with coordinates of 2, 8 and 32 are unnecessary, but they do no harm, so they are left in for golfing reasons. The fact that the length, width and depth of the cubies are different: (1,4,16) means it is easy to detect if they are in the right place but with wrong orientation.
Each cubie is tracked as it is moved by the faceturns. If the coordinate of a cubie in the axis corresponding to the face (multiplied by e=-1 for U,F,R or e=1 for D,B,L) is positive, then it will be rotated by swapping the coordinates in the other 2 axis and applying an appropriate sign change to one of the coordinates. This is controlled by multiplying by e*d.
The input sequence is scanned in reverse order. This makes no difference, so long as the "normal" rotations are performed anticlockwise instead of clockwise. The reason for this is so that if a ' symbol is found, the value of d can be changed from 1 to -1 in order to cause rotation of the following face in the opposite direction.
Ungolfed in test program
f=->s{n=0                                      #number of repeats=0
  a=[]                                         #empty array for solved position
  b=[]                                         #empty array for current position
  64.times{|i|
    a<<j=[(i&48)-16,(i&12)-4,i%4-1]            #generate 64 cubies and append them to the solved array
    b<<j*1                                     #duplicate them and append to active array
  }
  d=1                                          #default rotation direction anticlockwise (we scan the moves in reverse)
  (                                            #start of UNTIL loop
    n+=1                                       #increment repeat counter
    s.reverse.chars{|c|                        #reverse list of moves and iterate through it
      m="UFRDBL".index(c)                      #assign move letter to m (for ' or any other symbol m is false)
      m ?                                      #if a letter
        (e=m/3*2-1                             #e=-1 for UFR, 1 for DBL
        b.each{|j|                             #for each cubie
          j[m%=3]*e>0&&                        #m%=3 picks an axis. If the cubie is on the moving face of the cube
         (j[m-2],j[m-1]=j[m-1]*e*d,-j[m-2]*e*d)#rotate it: exchange the coordinates in the other 2 axes and invert the sign of one of them according to direction
        }                                      #as per the values of e and d.
        d=1                                    #set d=1 (in case it was -1 at the start of the b.each loop)
      ):
      d=-1                                     #ELSE the input must be a ', so set d=-1 to reverse rotation of next letter
    }
   )until n>0&&a==b                            #end of UNTIL loop. continue until back at start position a==b
n}                                             #return n

p f["FF'"]               #      1
p f["R"]                 #      4
p f["RUR'U'"]            #      6
p f["LLUUFFUURRUU"]      #     12
p f["LUFFRDRBF"]         #     56
p f["LF"]                #    105
p f["UFFR'DBBRL'"]       #    120
p f["FRBL"]              #    315

Cubically, 9 6 bytes
¶-7)8%

Try it online! (Nonworking until Dennis updates the TIO Cubically interpreter)
Explanation:
¶-7)8%
¶       read a string, insert into code
 -7     add 1 to notepad (subtracts the 7th face "sum" from notepad, defaulted to -1)
   )8   jump back to start of code if cube unsolved
     %  print notepad

This language will dominate all rubiks-cube challenges >:D

All these new-fangled esolangs. Back in my day, -7 meant subtract seven not add one angrily shakes walker

@cairdcoinheringaahing Indeed. :P Added some explanation around that.

Clojure, 359 bytes
This might be my 2nd longest codegolf. Realizing I could drop trailing zeros from vectors A to F made me very happy :D
#(let[I(clojure.string/replace % #"(.)'""$1$1$1")D(range -2 3)S(for[x D y D z D][x y z])A[0 1]B[0 0 1]C[1]D[-1]E[0 -1]F[0 0 -1]](loop[P S[[n R]& Q](cycle(map{\F[A[B A D]]\B[E[F A C]]\L[D[C B E]]\R[C[C F A]]\U[B[E C B]]\D[F[A D B]]}I))c 0](if(=(> c 0)(= P S))(/ c(count I))(recur(for[p P](if(>(apply +(map * n p))0)(for[r R](apply +(map * r p)))p))Q(inc c)))))

Less golfed:
(def f #(let [I (clojure.string/replace % #"(.)'""$1$1$1")
              D [-2 -1 0 1 2]
              S (for[x D y D z D][x y z])
              L   {\F [[ 0  1  0][[0  0  1][ 0 1  0][-1  0 0]]]
                   \B [[ 0 -1  0][[0  0 -1][ 0 1  0][ 1  0 0]]]
                   \L [[-1  0  0][[1  0  0][ 0 0  1][ 0 -1 0]]]
                   \R [[ 1  0  0][[1  0  0][ 0 0 -1][ 0  1 0]]]
                   \U [[ 0  0  1][[0 -1  0][ 1 0  0][ 0  0 1]]]
                   \D [[ 0  0 -1][[0  1  0][-1 0  0][ 0  0 1]]]}]
          (loop [P S c 0 [[n R] & Q] (cycle(map L I))]
            (if (and (> c 0) (= P S))
              (/ c (count I))
              (recur (for[p P](if(pos?(apply +(map * n p)))
                                (for[r R](apply +(map * r p)))
                                p))
                     (inc c)
                     Q)))))

This simply implements 3D rotations of selected subsets of 5 x 5 x 5 cube. Originally I was going to use 3 x 3 x 3 and it took me a while to realize why I wasn't getting correct results. Good test cases! Some extra bytes for fist encoding "RUR'U'" as "RURRRUUU".

Clean, 255 bytes
Derived separately from the almost-identical Haskell answer as an answer to this question which was closed as a duplicate when it was almost finished, so I posted the answer here.
import StdEnv,StdLib
a=[-2..2];b=diag3 a a a
?m=iter(size m*2-1)\p=:(x,y,z)=case m.[0]of'F'|z>0=(y,~x,z);'U'|y>0=(~z,y,x);'R'|x>0=(x,z,~y);'B'|z<0=(~y,x,z);'D'|y<0=(z,y,~x);'L'|x<0=(x,~z,y);_=p
$l=length(takeWhile((<>)b)(tl(iterate(map(sseq(map?l)))b)))+1

Try it online!


text:
Enumerate rhyme schemes
A "rhyme scheme" is a string of letters a to z, such that the first occurrences of the characters are in ascending order (without gaps), starting from a. For example (with first occurrences marked):
abccdbebdcfa
^^^ ^ ^   ^

The number of rhyme schemes of length N is given by the Bell numbers B(N). (OEIS A000110)
The Challenge
Your task is to implement an enumeration of these rhyme schemes, i.e. a bijective mapping from integers to rhyme schemes. You're given a positive integer N <= 26, as well as a non-negative integer 0 <= i < B(N). Alternatively, you can use the range 1 <= i <= B(N). You should output a rhyme scheme of length N, such that every i yields a different string.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
You may use either lower or upper case letters (consistently).
Your code must be able to handle any valid input in reasonable amount of time (e.g. not more than a few hours for N = 26, worst case i). This should allow solutions that scale exponentially with N (for small bases), even in slow languages but prohibit solutions that scale linearly with i (i.e. B(N)). In particular, that means you cannot just iterate through all valid rhyme schemes of length N until you've discard i schemes.
Standard code-golf rules apply.
Examples
The exact assignment of the i to schemes (i.e. the order of the schemes for a given N) is up to you. But say you chose lexicographical ordering, your solution should correspond to the following table (with - denoting invalid input):
N\i 1    2    3    4    5    6    7    8    9    10   11   12   13   14   15
1   a    -    -    -    -    -    -    -    -    -    -    -    -    -    -
2   aa   ab   -    -    -    -    -    -    -    -    -    -    -    -    -
3   aaa  aab  aba  abb  abc  -    -    -    -    -    -    -    -    -    -
4   aaaa aaab aaba aabb aabc abaa abab abac abba abbb abbc abca abcb abcc abcd

Here is a short CJam script which generates all valid rhyme schemes for any given length (but don't try more than 10 or you'll wait a while).
Related Challenges

Translate a Glypho program
Check if words are isomorphs

I might put a bounty on a (well-golfed) polynomial-time solution (in N), provided that doesn't turn out to be fairly trivial and I was just too stupid to find it.

Although the bounty is up for polynomial time solutions, I'd still like to see exponential-time solutions that meet the time limit. (My own Mathematica reference implementation would currently still win the challenge.)

B(26) is the smallest Bell number that doesn’t fit in a 64-bit integer. Meanie. :-(

CJam, 68 66 bytes
r~:W)1a*{__(;\);_,,.*.+}W(*r~{X@\=_2$\/:CX<!{X:C):X;}&C*-C'a+o}W*;

Try it online.
This is my first CJam program. It started life as a port of my Perl solution and was initially over 130 bytes long. Further golfing suggestions are welcome.
As with my Perl program, it is in two parts.
Part 1:
r~:W                                         | Read the first input (n) and store it in W
    )1a*                                     | Create an array of n+1 1s
        {              }W(*                  | Repeat n-1 times:
         __                                  | Duplicate array twice
           (;\);                             | Remove first element of 1st array. Swap
                                             | arrays. Remove last element of 2nd array
                _,,                          | Duplicate array. Count items. Create range
                   .*.+                      | Multiply arrays. Add 1st array to result

Part 2:
r~                                           | Read the second input (i)
   {                                  }W*    | Repeat n times:
    X@                                       | Push y (initially 1). Bring item 2 (last array) to top
     \=                                      | Swap top two items. Pop array[y] (v)
       _2$                                   | Duplicate v. Copy item 2 (i) to top
          \/:CX                              | Swap i & v. i/v. Store in C (c). Push y
               <!{       }&                  | If !(i/v < c):
                  X:C):X;                    | c = y. ++y (store in X)
                           C*-C'a+o          | i -= c * v. Push y. Push "a". Add c. Print
                                         ;   | Discard top item (integer 0)

To debug the arrays created by Part 1 add ]_`o~ between Parts 1 & 2. If n is 5, the arrays will look like this: [[1 1 1 1 1 1] [1 2 3 4 5] [2 5 10 17] [5 15 37] [15 52]]. The 0 indices of each array aren't used, they just make it easier by not having to calculate offsets. The arrays are calculated like this:
[2 5 10 17] [2 5 10 17] [2 5 10 17]        | Duplicate twice
[2 5 10 17] [2 5 10 17] [5 10 17]          | Discard first item of array
[2 5 10 17] [5 10 17] [2 5 10 17]          | Swap last two arrays
[2 5 10 17] [5 10 17] [2 5 10]             | Discard last item of array
[2 5 10 17] [5 10 17] [2 5 10] [2 5 10]    | Duplicate array
[2 5 10 17] [5 10 17] [2 5 10] 3           | Count items in array
[2 5 10 17] [5 10 17] [2 5 10] [0 1 2]     | Integer to range 0 - n-1
[2 5 10 17] [5 10 17] [0 5 20]             | Multiply arrays [2*0 5*1 10*2]
[2 5 10 17] [5 15 37]                      | Add arrays [5+0 10+5 17+20]

It keeps a copy of the old array while calculating the next one. The arrays are read and discarded in reverse order by Part 2.

Python 2, 153
u=[1]*999;i=60;exec"u[i]=i%30*u[i-30]+u[i-29];i+=1;"*900
def x(l,n,a=0):m=u[30*l+a];c=n>=a*m;return'.'*l and chr(65+min(n/m,a))+x(l-1,[n%m,n-m*a][c],a+c)

It uses alphabetical order and 0-based indexing.
Let l denote the length of a suffix of the letters and a denote the number of distinct letters that were used in the preceding part. Then a function p(l,a) that calculates the number of ways to select the remaining letters could be 40 bytes:
p=lambda l,a:l<1or a*p(l-1,a)+p(l-1,a+1)

However, this is too slow for the challenge, so instead the necessary values are precalculated and stored in the u array. At each stage of the calculation, if the next letter is the one of the a already used, the n = k * p(l - 1, a) + n' where k is the 0-indexed letter of the alphabet and n' is the value of n for the next function call, which contains the information about the remaining letters. If a new letter is used, then n = a * p(l - 1, a) + n'.

How long does it take for worst case input?

@MichaelKlein A negligible amount of time.

This is exactly what I was planning to do (except I would have done it with JS). Nice job! +1

Haskell (GHC 7.10), 150 bytes
s=(1,\_->[]):s
k!((y,b):l@((x,a):_))|let h i|i<x=k:a i|(p,q)<-divMod(i-x)y=p:b q=(x+k*y,h):(k+1)!l
n#i=(['a'..]!!).fromEnum<$>snd(iterate(0!)s!!n!!0)i

The operator n # i computes the ith (zero-indexed) rhyme scheme of length n.  It runs in O(n²) (big-integer) operations, taking advantage of Haskell’s lazy infinite lists for automatic memoization.  Sample runs:
*Main> 26 # 0
"abcdefghijklmnopqrstuvwxyz"
*Main> 26 # 1
"abcdefghijklmnopqrstuvwxya"
*Main> 26 # 2
"abcdefghijklmnopqrstuvwxyb"
*Main> 26 # 49631246523618756271
"aaaaaaaaaaaaaaaaaaaaaaaabb"
*Main> 26 # 49631246523618756272
"aaaaaaaaaaaaaaaaaaaaaaaaab"
*Main> 26 # 49631246523618756273
"aaaaaaaaaaaaaaaaaaaaaaaaaa"
*Main> [1 # i | i <- [0..0]]
["a"]
*Main> [2 # i | i <- [0..1]]
["ab","aa"]
*Main> [3 # i | i <- [0..4]]
["abc","aba","abb","aab","aaa"]
*Main> [4 # i | i <- [0..14]]
["abcd","abca","abcb","abcc","abac","abaa","abab","abbc","abba","abbb","aabc","aaba","aabb","aaab","aaaa"]

(If the maximum N were 25 instead of 26, the .fromEnum could be removed, because B(25) fits in a 64-bit Int.)

Looks great. Would you mind adding a less golfed version for easier grokking?

Perl 257 + 1 (-p flag) = 258
Perl 182 + 10 (-pMbignum flags) = 192
($n,$i)=split;@m=[@a=(1)x($n+1)];while($a[2]){push@m,[@a=map{$a[$_]*$_+$a[$_+1]}0..$#a-1]}$_='';$y=1;while($w=pop@m){$c=int($i/($v=$$w[$y]));$c=$y++if($c>=$y);$i-=$c*$v;$_.=chr$c+65}

Thanks to dev-nul for saving many bytes! I've now rewritten it based on what I learnt from doing the CJam version.
Calculates the rhyme in ascending alphabetical order, 0 indexed.
Two parts: Part 1 is 128 90 bytes and calculates a matrix for Part 2. Part 2 is 129 92 bytes and does some simple maths to calculate each letter. If I could get rid of the matrix and replace it with two simple numbers, I could calculate a single path through the matrix for each number and save a lot of bytes! Apparently, that idea doesn't work!
Unfortunately, it doesn't output the right rhymes for values of i higher than 9007199254740992, but it works beautifully for low values! I've added the Bignum library at a cost of 11 bytes. It's run from the command line with perl -pMbignum bell-rhyme.pl. -pMbignum  = 10 bytes. It's also very fast for any input value.

Oracle SQL 11.2, 412 284 283 bytes
WITH a AS(SELECT CHR(96+LEVEL)d,LEVEL b FROM DUAL CONNECT BY LEVEL<=:i),v(s,c,n)AS(SELECT d,1,1 FROM a WHERE b=1 UNION ALL SELECT s||d,b,LENGTH(REGEXP_REPLACE(s||d,'([a-z])\1+','\1'))FROM v,a WHERE(b<=n OR b=c+1)AND LENGTH(s)<:n)SELECT s FROM v WHERE:n=LENGTH(s)AND:i<=:n ORDER BY 1;

Unfortunately it only runs up to a length of 8.
Any greater value results in : ORA-01489: result of string concatenation is too long
Un-golfed
WITH a AS(SELECT CHR(96+LEVEL)d,LEVEL b FROM DUAL CONNECT BY LEVEL<=:i),
v(s,c,n) AS
(
  SELECT d,1,1 FROM a WHERE b=1
  UNION ALL
  SELECT s||d,b,LENGTH(REGEXP_REPLACE(s||d,'([a-z])\1+','\1'))
  FROM v,a
  WHERE (b<=n OR b=c+1) AND LENGTH(s)<:n
)
SELECT s FROM v WHERE LENGTH(s)=:n AND :i<=:n ORDER BY 1;

The a view generate the :i letters in column a and their value in b.
The recursive view v takes the string being constructed as parameter v,
the value of the last letter used in c and the value of the greatest letter used in n. The n parameter is equal to the length of the string without any duplicate letter, thats what the regex is for.
A letter is valid if its value is <= the value of the greatest letter already used or it is the next letter to be used.
Somehow the query needs the LENGTH(s)<:n part to run, I must be missing something in how the query works.
The main SELECT takes care of filtering out the invalid inputs and the shorter strings built before the length targeted is reached.
412 bytes version
WITH a AS(SELECT * FROM(SELECT d,b,ROW_NUMBER()OVER(PARTITION BY b ORDER BY d)l FROM(SELECT CHR(64+DECODE(MOD(LEVEL,:i),0,:i,MOD(LEVEL,:i)))d,CEIL(LEVEL/:i)b FROM DUAL CONNECT BY LEVEL<=:i*:n))WHERE l<=b),v(s,c,p)AS(SELECT d,1,l FROM a WHERE b=1 UNION ALL SELECT s||d,c+1,l FROM v,a WHERE c+1=b AND(l<=LENGTH(REGEXP_REPLACE(s,'([A-Z])\1+','\1'))OR l=p+1))SELECT s FROM v WHERE LENGTH(s)=:n AND :i<=:n ORDER BY 1;

Do not try the 412 bytes query with 26. It puts the database in restricted mode, at least on my xe version running in a docker container on a macbook. I could try on the exadata at work, but sadly I still need to work for a living.

Mathematica, 136 bytes
(For[j=2^#-1;t=#2,c=1;m=0;x=t;r=If[#>0,++m,c*=m;d=x~Mod~m+1;x=⌊x/m⌋;d]&/@j~IntegerDigits~2;;c<=t,t-=c;--j];FromCharacterCode[r+64])&

For completeness, here is my golfed reference implementation. As opposed to the existing answers this does not run in polynomial time (it's exponential in N with base 2) but does meet the time constraint (the worst case would still run in under half an hour).
The idea is this:

For each rhyme scheme we can identify the positions where the maximum character so far increases:
ABCDEFGHDIJDEKBBIJEIKHDFII
^^^^^^^^ ^^  ^

We can treat those markings as a binary number which makes it easy to iterate over all such structures. We need to iterate from 2n-1 to 2n (or the other way round) which is where the exponential time complexity comes from.
For each such structure it's easy to determine how many such strings there are: only the gaps between the markings can be freely chosen, and the maximum in front of the gap tells us how many different characters are valid in each position. This is a simple product. If this number is smaller than i, we subtract it from i. Otherwise, we've found the structure of the requested rhyme scheme.
To enumerate the schemes in the given structure, we simply represent i (or what remains of it) as a mixed-base number, where the weights of the digits are determined by the number of allowed characters in the remaining positions.

I wonder if this would allow for a shorter solution in some of the other languages that were submitted since it doesn't require any memoisation or precomputation.

source: Stack Exchange

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

sort: votes


text:
Rearranging the sequence
Introduction
Let's observe the following sequence (non-negative integers):
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ...

For example, let's take the first three numbers. These are 0, 1, 2. The numbers used in this sequence can be ordered in six different ways:
012   120
021   201
102   210

So, let's say that F(3) = 6. Another example is F(12). This contains the numbers:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

Or the concatenated version:
01234567891011

To find the number of ways to rearrange this, we first need to look at the length of this string. The length of this string is 14. So we compute 14!. However, for example the ones can exchange places without disrupting the final string. There are 2 zeroes, so there are 2! ways to exhange the zeroes without disrupting the order. There are also 4 ones, so there are 4! ways to switch the ones. We divide the total by these two numbers:
This has 14! / (4! × 2!) = 1816214400 ways to arrange the string 01234567891011. So we can conclude that F(12) = 1816214400.
The task
Given N, output F(N). For the ones who don't need the introduction. To compute F(N), we first concatenate the first N non-negative integers (e.g. for N = 12, the concatenated string would be 01234567891011) and calculate the number of ways to arrange this string.
Test cases
Input:   Output:
0        1
1        1
2        2
3        6
4        24
5        120
6        720
7        5040
8        40320
9        362880
10       3628800
11       119750400
12       1816214400
13       43589145600
14       1111523212800
15       30169915776000

Note
Computing the answer must be computed within a time limit of 10 seconds, brute-forcing is disallowed.
This is code-golf, so the submission with the least amount of bytes wins!

Is the output for 10 correct? It feels like it should be less than 10!, since that's where the repeating digits start.

@Geobits The first 10 digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Ten different digits, so the result is 10!.

Ah, right. I think the 0 case was throwing my count off (stupid empty strings).

You only need to support the test cases that your language can handle. Natively? This needs one more upvote to count as standard loophole...

@Dennis Hmmm, good point. I have deleted the rule in the post.

No need to worry about that anymore. The loophole proposal was at +4 when I posted the comment. It is at +9 now.

Here's an interesting math question about this puzzle: What is the value of F(N) relative to N!? There are a number of values of N for which F(N)/F(N-1) < N, but it is usually slightly greater. I'm pretty sure that F(N) is not O(N!) and that log F(N) is O(log N!) but those are just hunches...

Jelly, 17 15 bytes
R’DFµ=€QS;@L!:/

Try it online! or verify all test cases at once.
How it works
R’DFµ=€QS;@L!:/    Main link. Input: n

R                  Yield [1, ..., n] for n > 0 or [0] for n = 0.
 ’                 Decrement. Yields [0, ..., n - 1] or [-1].
  D                Convert each integer into the list of its decimal digits.
   F               Flatten the resulting list of lists.
    µ              Begin a new, monadic chain. Argument: A (list of digits)
       Q           Obtain the unique elements of A.
     =€            Compare each element of A with the result of Q.
                   For example, 1,2,1 =€ Q -> 1,2,1 =€ 1,2
                                           -> [[1, 0], [0, 1], [1, 0]]
        S          Sum across columns.
                   This yields the occurrences of each unique digit.
         ;@L       Prepend the length of A.
            !      Apply factorial to each.
             :/    Reduce by divison.
                   This divides the first factorial by all remaining ones.

Is this really Jelly? I see to many ASCII characters :-P

They always manage to sneak in somehow...

ES6, 118 81 78 bytes
n=>[...[...Array(n).keys()].join``].map(c=>r/=(o[c]=-~o[c])/i++,o=[],i=r=1)&&r

Someone's bound to tell me there's a shorter way of concatenating the numbers up to n.
Saved a cool 37 bytes by taking @edc65's idea and running it on steroids. (Save an extra byte by using '|' instead of && but that limits the result to 31 bits.)
Edit: Saved 3 further bytes again thanks to @edc65.

Did not find a way to shorten the digits concatenation. But all the rest can be shorter

Save 2 bytes with reduce: n=>[...[...Array(n).keys()].join\`].reduce((r,c,i)=>r*++i/(o[c]=-~o[c]),1,o=[])`

Wow! but 78 is better: n=>[...[...Array(n).keys()].join``].map(c=>r/=(o[c]=-~o[c])/i++,o=[],i=r=1)&&r

@user81655 Huh, I was sure someone told me that map would always work out cheaper.

@edc65 r/=(...)/i++ is more accurate than r*=i++/(...)? That's the most ludicrous golf I've ever seen!

I had to stop for a moment, because I thought you had a regex in there.

APL (Dyalog Extended), 13 bytes
×/2!/+\⎕D⍧⍕⍳⎕

Try it online!
A full program. Uses ⎕IO←0.
How it works
×/2!/+\⎕D⍧⍕⍳⎕
            ⎕  ⍝ Take input from stdin (N)
           ⍳   ⍝ Generate range 0..N-1
          ⍕    ⍝ Stringify the entire array (S)
               ⍝ (The result has spaces between items)
       ⎕D      ⍝ The character array '0123456789'
         ⍧     ⍝ Count occurrences of each digit in S
×/2!/+\        ⍝ Calculate multinomial:
     +\        ⍝   Cumulative sum
  2!/          ⍝   Binomial of consecutive pairs
×/             ⍝   Product

The multinomial calculation comes from the following fact:
$$
\frac{(a_1 + a_2 + \cdots + a_n)!}{a_1! a_2! \cdots a_n!} = \frac{(a_1 + a_2)!}{a_1! a_2!} \times \frac{(a_1 + a_2 + \cdots + a_n)!}{(a_1 + a_2)! a_3! \cdots a_n!}
$$
$$
= \frac{(a_1 + a_2)!}{a_1! a_2!} \times \frac{(a_1 + a_2 + a_3)!}{(a_1 + a_2)! a_3!} \times \frac{(a_1 + a_2 + \cdots + a_n)!}{(a_1 + a_2 + a_3)! \cdots a_n!}
$$
$$
= \cdots = \binom{a_1 + a_2}{a_1} \binom{a_1 + a_2 + a_3}{a_1 + a_2} \cdots \binom{a_1 + \cdots + a_n}{a_1 + \cdots + a_{n-1}}
$$

And this is why programmers should learn mathematics.

@Anonymous … and use a mathematically inclined programming language.

MATL, 21 bytes
:qV0h!4Y2=sts:pw"@:p/

Try it online!
Explanation
:q     % implicitly input N, and generate vector [0, 1, ..., N-1]
V      % convert to string representation of numbers. Contains spaces,
       % but no matter. Only characters '0', ..., '9' will be counted
0h     % append 0 character (not '0'), so that string is never empty
!      % convert string to column char array
4Y2    % string '0123456789' (row char array)
=      % test all pairs for equality
s      % sum each column. For N = 12 this gives [2, 4, 1, 1, ..., 1]
t      % duplicate
s      % compute sum. For N = 12 this gives 14
:p     % factorial
w      % swap. Now vector [2, 4, 1, 1, ..., 1] is on top
"      % for each number in that vector
  @:p  %   factorial
  /    %   divide
       % implicitly end loop
       % implicitly display

@Adnan Solved. And with fewer bytes :-)

Looks very nice! :)

@Adnan Thanks! I've added an explanation

Python 2, 197 Bytes (edit: saved 4 bytes, thanks Thomas Kwa!)
import math
l,g,f,p,r,s=[],[],math.factorial,1,range,str
for x in r(int(input())):l.append(s(x))
l="".join(l)
for y in r(10):b=s(l).count(s(y));g.append(f(b));
for c in g:p*=y
print f(int(len(l)))/p

Ungolfed:
import math

l=[] #list of the numbers from 0 to n
exchange_list=[] #numbers that can be exchanged with each other, ie      repeats

multiplied = 1 #for multiplying the digits by each other
n = int(input())

for x in range(n): #put all the numbers from 0-n into the list
    l.append(str(x))

l = "".join(l) #put all the digits in a string to remove repeats

for x in range(10): #look at all the digits and check how many are in the     list/string
    count = str(l).count(str(x))
    if count > 1: #if there is more than 1 of the digit, put the factorial of the amount of -
        exchange_list.append(math.factorial(count)) # - appearances into the exchange list.

for x in exchange_list: #multiply all the values in the list by each other
    multiplied*=x

print math.factorial(int(len(l)))/multiplied #print the factorial of the  length of the string
#divided by the exchanges multiplied

Welcome to Programming Puzzles and Code Golf! This answer was flagged as VLQ (very low quality), I suspect because it does not contain any explanation or ungolfed version, which are the norm here. Assuming your answer works, and you improve it from being "code only", it seems quite good!

range(0,10) can be range(10).

Python 2, 142 137 101 97 bytes
(Thanks @adnan for the suggestion about input)
(Applied the incremental calculation from the C version)
f=1;v=10*[0]
for i in range(input()):
 for h in str(i):k=int(h);v[k]+=1;f=f*sum(v)/v[k]
print f

Original version using factorial
import math
F=math.factorial
v=10*[0]
for i in range(input()):
 for h in str(i):v[int(h)]+=1
print reduce(lambda a,x:a/F(x),v,F(sum(v)))

Really, the only golfing in the above is calling math.factorial F and leaving out some spaces, so there is probably a shorter python solution.
If explanation is needed, v maintains a count of the frequency of each digit; the count is updated for each digit in each number in the indicated range.
In the original version, we compute the number of permutations using the standard formula (Σfi)!/π(fi!). For the current version, this computation is done incrementally by distributing the multiplies and divides as we see the digits. It might not be obvious that the integer divide will always be exact, but it is easy to prove based on the observation that each division by k must follow k multiplies of consecutive integers, so one of those multiplies must be divisible by k. (That's an intuition, not a proof.)
The original version is faster for large arguments because it does only 10 bignum divides. Although dividing a bignum by a small integer is faster than dividing a bignum by a bignum, when you have thousands of bignum divides, it gets a bit sluggish.

f=fsum(v)/v[k]  --> f=sum(v)/v[k] saves a byte

@superflux: but it is not the same meaning.

CJam, 21 19 bytes
ri,s_,A,s@fe=+:m!:/

Test it here.
Explanation
ri   e# Read input and convert to integer N.
,    e# Get a range [0 1 ... N-1].
s    e# Convert to string, flattening the range.
_,   e# Duplicate and get its length.
A,s  e# Push "012345789".
@fe= e# Pull up the other copy of the string and count the occurrences of each digit.
+    e# Prepend the string length.
:m!  e# Compute the factorial of each of them.
:/   e# Fold division over the list, dividing the factorial of the length by all the other
     e# factorials.

JavaScript (ES6), 100
n=>(f=[...[...Array(n).keys()].join``].map(c=>(k[c]=~-k[c],p*=i++),i=p=1,k=[]),k.map(v=>p/=f[~v]),p)

Test

F=n=>(f=[...[...Array(n).keys()].join``].map(c=>(k[c]=~-k[c],p*=i++),i=p=1,k=[]),k.map((v,i)=>p/=f[~v]),p)

// Less golfed
U=n=>( // STEP 1, count digits, compute factorials
      f= // will contain the value of factorials 1 to len of digits string
      [...[...Array(n).keys()].join``] // array of cancatenated digits
      .map(c=> // execute the following for each digit
           (
            k[c]=~-k[c], // put in k[c] the repeat count for digit c, negated
            p*=i++       // evaluate factorial, will be stored in f
           ),i=p=1,k=[]),// initialisations
       // at the end of step 1 we have all factorials if f and max factorial in p
       // STEP 2, divide the result taking into account the repeated digits
      k.map(v=>p/=f[~v]), // for each digit, divide p by the right factorial (~v === -v-1)
  p // return result in p
)

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

for(j=0;j<=15;j++) console.log(j+' '+F(j))

Isn't k[c]=~-k[c] synonymous with --k[c]?

@usandfriends no, when k[c] is undefined --k[c] is NaN

Ooh, nice array of factorials.

... although you don't need it. See my latest update.

Pyth, 18 bytes
/F.!M+lJ.njRTQ/LJT

Try it online: Demonstration
/F.!M+lJ.njRTQ/LJT   implicit: Q = input number
          jRTQ       convert each number in [0, ..., Q-1] to their digits
        .n           flatten to a single list
       J             store this list in J
              /LJT   for each digit count the number of appearances in J
     +lJ             prepend the length of J
  .!M                compute the factorial for each number
/F                   fold by division

Haskell, 92 bytes
import Data.List
h n|l<-sort$show=<<[0..n-1]=foldl1 div$product.map fst.zip[1..]<$>l:group l

Usage example: h 12 -> 1816214400.
How it works
l<-sort$show=<<[0..n-1]       -- bind l to the sorted concatenated string
                              -- representations of the numbers from 0 to n-1
                              -- e.g. n=12 -> "00111123456789"

               l: group l     -- group the chars in l and put l itself in front
                              -- e.g. ["00111123456789","00","1111","2",..."9"]
            <$>               -- map over this list
    product.map fst.zip[1..]  -- the faculty the length of the sublist (see below)
                              -- e.g. [87178291200,2,24,1,1,1,..,1]
foldl1 div                    -- fold integer division from the left into this list
                              -- e.g. 87178291200 / 2 / 24 / 1

                              -- Faculty of the length of a list:
                  zip[1..]    -- make pairs with the natural numbers
                              -- e.g. "1111" -> [(1,'1'),(2,'1'),(3,'1'),(4,'1')]
          map fst             -- drop 2nd element form the pairs
                              -- e.g. [1,2,3,4]
  product                     -- calculate product of the list

Perl 5, 108 bytes
sub f{eval join"*",@_,1}push@a,/./g for 0..<>-1;for$i(0..9){$b[$i]=grep/$i/,@a}say f(1..@a)/f map{f 1..$_}@b

Many thanks to dev-null for saving me 17 bytes, and to japhy for the factorial idea.

Perl 6, 117 bytes
say $_ <2??1!!permutations(+[(my@n=^$_ .join.comb)]).elems÷[*] ([*] 2..$_ for @n.classify(&unique).values)for lines

and in a more readable fasion
for (lines) -> $number {
    say 1 and next if $number < 2;
    my @digits = (^$number).join.comb;
    my @duplicates = @digits.classify(&unique).values;
    my $unique_permutations = permutations(+@digits).elems ÷ [*] ([*] 2..$_ for @duplicates);
    say $unique_permutations;
}

C, 236 174 138 121 bytes
Much credit to rici, for massive reduction of bytes.
long long d,f=1;j,s=1,n,b[10]={1};main(d){for(scanf("%d",&n);n--;)for(j=n;j;j/=10,f*=++s)d*=++b[j%10];printf("%Ld",f/d);}

Ungolfed
long long d,f=1;
j,s=1,n,b[10]={1};

main(d)
{
    scanf("%d",&n); /* get input */
    for(;n--;) /* iterate through numbers... */
        for(j=n;j;j/=10,f*=++s) /* iterate through digits, sum up and factorial */
            d*=++b[j%10]; /* count and factorial duplicates */
    printf("%Ld",f/d); /* print out result */
}

Try it here.

You could save 43 characters by not mucking around with -lm. Just count the digits as you find them: #define L long long L d;i,j,k,m,n,s=1,b[10]={1};L f(n){return n?n*f(n-1):1;}main(d){for(scanf("%d",&n);i<n;)for(j=i++;j;j/=10)++b[j%10],++s;for(;m<10;)d*=f(b[m++]);printf("%Ld",f(s)/d);}

You could also count them in the loop where you compute d: for(;m<10;)s+=b[m],d*=f(b[m++]) but I think that's a couple more bytes.

That's brilliant. I'll combine with my current golfing efforts and edit.

Nice: take a look at mine to see how to integrate the factorial computation into the original loop, which has the advantage of working on a slightly larger range if you don't have arbitrary-precision arithmetic. I think that's another 20 bytes to shave.

C/bc, 233 121 112 bytes (assuming 3 byte penalty for |bc)

Inspired by Cole Cameron, removed the hacky character manipulation and just do arithmetic on the argument value.

Changed to scanf from using arg vector.
 C[10]={1},n=1,k,t;main(){for(scanf("%d",&k);k--;)for(t=k;t;t/=10)printf("%d/%d*",++n,++C[t%10]);puts("1");}

Needs bc to actually do the arbitrary precision computation.
Ungolfed and warning free:
#include <stdio.h>
int main() {
  int C[10]={1},n=1,k,t;    /* 0 is special-cased */
  for(scanf("%d",&k);k--;)  /* For each integer less than k */
    for(int t=k;t;t/=10)    /* For each digit in t */
      printf("%d/%d*",++n,++C[t%10]);  /* Incremental choice computation */
  puts("1");                /* Finish the expression */
}

Illustrated (which I trust shows the algorithm):
$ for i in {0..15} 100 ; do printf %4d\  $i;./cg70892g<<<$i;done
   0 1
   1 1
   2 2/1*1
   3 2/1*3/1*1
   4 2/1*3/1*4/1*1
   5 2/1*3/1*4/1*5/1*1
   6 2/1*3/1*4/1*5/1*6/1*1
   7 2/1*3/1*4/1*5/1*6/1*7/1*1
   8 2/1*3/1*4/1*5/1*6/1*7/1*8/1*1
   9 2/1*3/1*4/1*5/1*6/1*7/1*8/1*9/1*1
  10 2/1*3/1*4/1*5/1*6/1*7/1*8/1*9/1*10/1*1
  11 2/1*3/2*4/1*5/1*6/1*7/1*8/1*9/1*10/1*11/1*12/2*1
  12 2/1*3/2*4/3*5/2*6/1*7/1*8/1*9/1*10/1*11/1*12/1*13/1*14/4*1
  13 2/1*3/1*4/2*5/3*6/4*7/2*8/1*9/1*10/1*11/1*12/1*13/1*14/1*15/2*16/5*1
  14 2/1*3/1*4/2*5/1*6/3*7/4*8/5*9/2*10/1*11/1*12/1*13/1*14/1*15/1*16/2*17/2*18/6*1
  15 2/1*3/1*4/2*5/1*6/3*7/1*8/4*9/5*10/6*11/2*12/1*13/1*14/1*15/1*16/1*17/2*18/2*19/2*20/7*1
 100 2/1*3/2*4/3*5/1*6/4*7/1*8/5*9/1*10/6*11/1*12/7*13/1*14/8*15/1*16/9*17/1*18/10*19/1*20/11*21/2*22/2*23/12*24/3*25/4*26/5*27/2*28/6*29/2*30/7*31/2*32/8*33/2*34/9*35/2*36/10*37/2*38/11*39/2*40/12*41/3*42/3*43/13*44/4*45/13*46/5*47/6*48/7*49/3*50/8*51/3*52/9*53/3*54/10*55/3*56/11*57/3*58/12*59/3*60/13*61/4*62/4*63/14*64/5*65/14*66/6*67/14*68/7*69/8*70/9*71/4*72/10*73/4*74/11*75/4*76/12*77/4*78/13*79/4*80/14*81/5*82/5*83/15*84/6*85/15*86/7*87/15*88/8*89/15*90/9*91/10*92/11*93/5*94/12*95/5*96/13*97/5*98/14*99/5*100/15*101/6*102/6*103/16*104/7*105/16*106/8*107/16*108/9*109/16*110/10*111/16*112/11*113/12*114/13*115/6*116/14*117/6*118/15*119/6*120/16*121/7*122/7*123/17*124/8*125/17*126/9*127/17*128/10*129/17*130/11*131/17*132/12*133/17*134/13*135/14*136/15*137/7*138/16*139/7*140/17*141/8*142/8*143/18*144/9*145/18*146/10*147/18*148/11*149/18*150/12*151/18*152/13*153/18*154/14*155/18*156/15*157/16*158/17*159/8*160/18*161/9*162/9*163/19*164/10*165/19*166/11*167/19*168/12*169/19*170/13*171/19*172/14*173/19*174/15*175/19*176/16*177/19*178/17*179/18*180/19*181/10*182/20*183/20*184/20*185/20*186/20*187/20*188/20*189/20*190/20*1

And, with the pipe through bc (and adding the computation of F(1000):
$ time for i in {0..15} 100 1000; do printf "%4d " $i;./cg70892g<<<$i|bc;done
   0 1
   1 1
   2 2
   3 6
   4 24
   5 120
   6 720
   7 5040
   8 40320
   9 362880
  10 3628800
  11 119750400
  12 1816214400
  13 43589145600
  14 1111523212800
  15 30169915776000
 100 89331628085599251432057142025907698637261121628839475101631496666431\
15835656928284205265561741805657733401084399630568002336920697364324\
98970890135552420133438596044287494400000000
1000 45200893173828954313462564749564394748293201305047605660842814405721\
30092686078003307269244907986874394907789568742409099103180981532605\
76231293886961761709984429587680151617686667512237878219659252822955\
55855915137324368886659115209005785474446635212359968384367827713791\
69355041534558858979596889046036904489098979549000982849236697235269\
84664448178907805505235469406005706911668121136625035542732996808166\
71752374116504390483133390439301402722573240794966940354106575288336\
39766175522867371509169655132556575711715087379432371430586196966835\
43089966265752333684689143889508566769950374797319794056104571082582\
53644590587856607528082987941397113655371589938050447115717559753757\
79446152023767716192400610266474748572681254153493484293955143895453\
81280908664541776100187003079567924365036116757255349569574010994259\
42252682660514007543791061446917037576087844330206560326832409035999\
90672829766080114799705907407587600120545365651997858351981479835689\
62520355320273524791310387643586826781881487448984068291616884371091\
27306575532308329716263827084514072165421099632713760304738427510918\
71188533274405854336233290053390700237606793599783757546507331350892\
88552594944038125624374807070741486495868374775574664206439929587630\
93667017165594552704187212379733964347029984154761167646334095514093\
41014074159155080290000223139198934433986437329522583470244030479680\
80866686589020270883335109556978058400711868633837851169536982150682\
22082858700246313728903459417761162785473029666917398283159071647546\
25844593629926674983035063831472139097788160483618679674924756797415\
01543820568689780263752397467403353950193326283322603869951030951143\
12095550653333416019778941123095611302340896001090093514839997456409\
66516109033654275890898159131736630979339211437991724524614375616264\
98121300206207564613016310794402755159986115141240217861695468584757\
07607748055900145922743960221362021598547253896628914921068009536934\
53398462709898222067305585598129104976359039062330308062337203828230\
98091897165418693363718603034176658552809115848560316073473467386230\
73804128409097707239681863089355678037027073808304307450440838875460\
15170489461680451649825579772944318869172793737462142676823872348291\
29912605105826175323042543434860948610529385778083808434502476018689\
05150440954486767102167489188484011917026321182516566110873814183716\
30563399848922002627453188732598763510259863554716922484424965400444\
85477201353937599094224594031100637903407963255597853004241634993708\
88946719656130076918366596377038503741692563720593324564994191848547\
42253991635763101712362557282161765775758580627861922528934708371322\
38741942406807912441719473787691540334781785897367428903185049347013\
44010772740694376407991152539070804262207515449370191345071234566501\
33117923283207435702471401696679650483057129117719401161591349048379\
16542686360084412816741479754504459158308795445295721744444794851033\
08800000000

real    0m0.246s
user    0m0.213s
sys     0m0.055s

This computed F(5000) -- an 18,592-digit number -- in under 10 seconds.
$ time ./cg70892g3<<<5000|BC_LINE_LENGTH=0 bc|wc -c
18593

real    0m9.274s
user    0m9.273s
sys     0m0.005s

05AB1E, 13 12 11 bytes
ÝD¨SāPr¢!P÷

Try it online!
Ý             # range [0..input]
 D            # duplicate
  ¨           # drop the last element
   S          # split into digits
    ā         # length range: [1..number of digits]
     P        # product (effectively a factorial)
      r       # reverse the stack
       ¢      # count occurences of each number in the list of digits
        !     # factorial of each count
         P    # product of those
          ÷   # divide the initial factorial by this product

Python 2, 123 bytes
import math
i,b,F="".join(map(str,range(input()))),1,math.factorial
for x in range(10):b*=F(i.count(`x`))
print F(len(i))/b

Try it online!

Convert the range of the input to a single string
Check how many times each of the numbers from 0 to 9 appears in the string and get the factorial for each then multiply them together
Divide the factorial of the length of the string by the number calculated in step 2

PowerShell, 125 bytes
(1..(($b=0..($args[0]-1)-join'').Length)-join'*'|iex)/((0..9|%{$c=[regex]::Matches($b,$_).count;1..($c,1)[!$c]})-join'*'|iex)

Takes input $args[0], subtracts 1, builds a range of integers from 0.. that number, -joins that together into a string, and saves it as $b. We take the .Length of that string, build another range from 1.. that length, -join those integers together with *, then pipe that to Invoke-Expression (similar to eval). In other words, we've constructed the factorial of the length of the number sequence based on the input. That's our numerator.
We divide that / by ...
Our denominator, which is constructed by taking a range 0..9 and sending it through a for-loop |%{...}. Each iteration, we set a helper variable $c equal to the number of times the current digit $_ appears within $b thanks to the .NET [regex]::matches call coupled with the .count attribute. We then construct a new range from 1.. up to that value, so long as it's non-zero. Yes, in many instances, this will result in a range 1..1, which evaluates to just 1. We take all of those and -join them together with *, then pipe that to Invoke-Expression again. In other words, we've constructed the product of the factorials of the number of occurrences of each digit.

NB
Handles input up to 90 without issue and in significantly less than a second.
PS C:\Tools\Scripts\golfing> .\rearranging-the-sequence.ps1 90
1.14947348910454E+159

PS C:\Tools\Scripts\golfing> Measure-Command {.\rearranging-the-sequence.ps1 90} | FL TotalMilliseconds
TotalMilliseconds : 282.587

... beyond that results in Infinity as output, since the length of the permutable string results in 170! which fits in the double datatype (7.25741561530799E+306), but 171! doesn't. PowerShell has a ... quirk ... that automatically up-casts from [int] to [double] in the case of overflow (provided you didn't explicitly cast the variable to start with). No, I don't know why it doesn't go to [long] for integer values.
If we did some explicit casting and manipulation (e.g., using [uint64], for unsigned 64-bit integers), we could get that higher, but it would significantly bloat the code as we would need to range up to 170-length with conditionals and then recast each multiplication from there onward. As the challenge doesn't specify an upper range, I'm presuming this to be adequate.

Perl6
perl6 -e 'sub p ($a) { my $x = $a.join.comb.classify(+*).values.map(*.elems).classify(+*).values.flatmap(*.list).flatmap((2..+*).list); my $y = 2..$a[*-1]; [/] $x.list * [*] $y.list }; p([1..11]).say'

Rather ungolfed at the moment - need sleep now.

Groovy, 156 bytes
def f(n){def s=(0..n-1).join('')
0==n?1:g(s.size())/s.inject([:]){a,i->a[i]=a[i]?a[i]+1:1;a}*.value.inject(1){a,i->a*g(i)}}
BigInteger g(n){n<=1?1:n*g(n-1)}

My humble first Code Golf solution. You can test it here.
And here's a more readable version:
def f(n) {
  def s = (0..n - 1).join('')                       // Store our concatented range, s
  0 == n ? 1 :                                      // Handle annoying case where n = 0
    fact(s.size()) / s.inject([:]) {                // Divide s.size()! by the product of the values we calculate by...
      a, i ->                                       // ...reducing into a map...
        a[i] = a[i] ? a[i] + 1 : 1                  // ...the frequency of each digit
        a                                           // Our Groovy return statement
    }*.value.inject(1) { a, i -> a * fact(i) }      // Finally, take the product of the factorial of each frequency value
}

BigInteger fact(n) { n <= 1 ? 1 : n * fact(n - 1) } // No built-in factorial function...

Quite straightforward, but there were a couple highlights for me:

Performing an inject/reduce from an array of chars to a Map<Character, Integer>. This was still a little complicated by the lack of a default value for the map values. This doubt this is possible, but if the map defaulted all values to 0, I could avoid the ternary which is necessary to avoid an NPE.
The Groovy spread operator (e.g. }*.value) is always fun to use

On annoying feature, however, was the necessity to declare the factorial function with the return type BigInteger. I was under the impression that Groovy wrapped all numerics in BigInteger or BigDecimal, but this might not be the case when it comes to return types. I'll have to experiment more. Without this return type explicitly stated, we get incorrect factorial values very quickly.

J, 33 bytes
(#(%*/)&:!&x:#/.~)@([:;<@":"0)@i.

Converts the range into a string of digits, counts each digits, and applies the multinomial coefficient to compute the result.
Usage
   f =: (#(%*/)&:!&x:#/.~)@([:;<@":"0)@i.
   (,.f"0) i. 16
 0              1
 1              1
 2              2
 3              6
 4             24
 5            120
 6            720
 7           5040
 8          40320
 9         362880
10        3628800
11      119750400
12     1816214400
13    43589145600
14  1111523212800
15 30169915776000

R, 118 bytes
About 8 months late to the party but thought I'd give it a go because it looked like an interesting challenge.
function(n,x=as.numeric(el(strsplit(paste(1:n-1,collapse=""),""))),F=factorial)`if`(n,F(sum(1|x))/prod(F(table(x))),1)

Try it on R-fiddle
Explained

Generate vector 0 ... n-1 and collapse it to a string: paste(1:n-1,collapse="")

Split string into its digits and convert to numeric(store as x): x=as.numeric(el(strsplit(...,"")))

To calculate the numerator we simply do factorial(sum(1|x)) which is just #digits!

To calculate the denominator we make use of table to construct a contingency table that list the frequencies. In the case of F(12) the table generated is:
0 1 2 3 4 5 6 7 8 9
2 4 1 1 1 1 1 1 1 1

Which means we can take the use factorial() (which by the way is vectorized) on the count and simply take the product: prod(factorial(table(x)))

Note: step 4 and 5 are only carried through if n>0 otherwise return 1.

Mathematica, 65 bytes
(Tr@IntegerLength[a=Range@#-1]+1)!/Times@@(Total[DigitCount@a]!)&

Could probably be golfed further.

Jelly, 11 bytes
Golfed Dennis' 15 byte Jelly answer...
ḶDFµW;ĠẈ!:/

A monadic Link accepting a non-negative integer which yields a positive integer.
Try it online! Or see the test suite.
How?
ḶDFµW;ĠẈ!:/ - Link: non-negative integer, N   e.g. 12
Ḷ           - lowered range            [0,1,2,3,4,5,6,7,8,9,10,11]
 D          - to decimal (vectorises)  [[0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[1,0],[1,1]]
  F         - flatten                  [0,1,2,3,4,5,6,7,8,9,1,0,1,1]
   µ        - start a new monadic chain - i.e. f(that)
    W       - wrap in a list           [[0,1,2,3,4,5,6,7,8,9,1,0,1,1]]
      Ġ     - group indices by values  [[1,12],[2,11,13,14],3,4,5,6,7,8,9,10]
     ;      - concatenate              [[0,1,2,3,4,5,6,7,8,9,1,0,1,1],[1,12],[2,11,13,14],3,4,5,6,7,8,9,10]
       Ẉ    - length of each           [14,2,4,1,1,1,1,1,1,1,1]
        !   - factorial (vectorises)   [87178291200,2,24,1,1,1,1,1,1,1,1]
          / - reduce by:
         :  -   integer division       1816214400

Ruby, 64 bytes
->n,*w{a=1;[*0...n].join.chars{|d|a=a*(w<<d).size/w.count(d)};a}

Try it online!

Stax, 12 bytes
éÄ\↑≈g→FP○░→

Run and debug it at staxlang.xyz!
Unpacked (14 bytes) and explanation:
r$c%|Fso:GF|F/
r                 Range [0..input)
 $                Stringify each and concat
  c               Copy atop the stack
   %|F            Factorial of length
      s           Swap original back to top
       o          Sort
        :G        Run lengths
          F       For each:
           |F       Factorial
             /      Divide running quotient by this factorial
                  Implicit print

Python 2, 134 bytes
s="".join(map(str,range(input())))
n=d=1
for i in range(1,len(s)+1):n*=i;d*=i**len([c for c in range(10)if s.count(`c`)>=i])
print n/d

Try it online!
An alternate approach...

Python 2, 190 bytes
from collections import*
g,n=range,int(input())
p=lambda r:reduce(lambda x,y:x*y,r,1)
f=lambda n:p(g(1,n+1))
s=''.join(str(i)for i in g(n))
c=Counter(s)
print(f(len(s))/p(f(c[i])for i in c))

Try it online!

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

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


text:
Print the Super Collatz numbers
The Collatz Sequence (also called the 3x + 1 problem) is where you start with any positive integer, for this example we will use 10, and apply this set of steps to it:
if n is even:
    Divide it by 2
if n is odd:
    Multiply it by 3 and add 1
repeat until n = 1

10 is even, so we divide by 2 to get 5. 5 is odd, so we multiply by 3 and add 1 to get 16. 16 is even, so cut it in half to get 8. Half of 8 is 4, half of 4 is 2, and half of 2 is 1. Since this took us 6 steps, we say that 10 has a stopping distance of 6.
A Super Collatz number is a number whose stopping distance is greater then the stopping distance of every number smaller than it. For example, 6 is a Super Collatz number since 6 has a stopping distance of 8, 5 has a stopping distance of 5, 4 has 2, 3 has 7, 2 has 1 and 1 has 0. (A006877 in the OEIS) You must take a number n as input, and output out all the Super Collatz numbers up to n.
Rules

Full Program or function is acceptable.
You can not precompute or hard-code the Super Collatz sequence.
You can take input in any reasonable format.
Output can be returned as a list from the function, or printed to STDOUT or a file. Whichever is most convenient.
Invalid inputs (non-numbers, decimals, negative numbers, etc.) result in undefined behavior.

Sample ungolfed python
def collatzDist(n):
    if n == 1:
        return 0
    if n % 2 == 0:
        return 1 + collatzDist(n / 2)
    return 1 + collatzDist((n * 3) + 1)

n = input()

max = -1
superCollatz = []
for i in range(1, n + 1):
    dist = collatzDist(i)
    if dist > max:
        superCollatz.append(i)
        max = dist

print superCollatz

Sample IO:
#in       #out
 4     --> 1, 2, 3
 50    --> 1, 2, 3, 6, 7, 9, 18, 25, 27
 0     --> invalid
 10000 --> 1, 2, 3, 6, 7, 9, 18, 25, 27, 54, 73, 97, 129, 171, 231, 313, 327, 649, 703, 871, 1161, 2223, 2463, 2919, 3711, 6171

Also here are the first 44 Super Collatz numbers:
1, 2, 3, 6, 7, 9, 18, 25, 27, 54, 73, 97, 129, 171, 231, 313, 327, 649, 703, 871, 1161, 2223, 2463, 2919, 3711, 6171, 10971, 13255, 17647, 23529, 26623, 34239, 35655, 52527, 77031, 106239, 142587, 156159, 216367, 230631, 410011, 511935, 626331, 837799

Also, if anyone can find a number with a stopping distance of infinity (never reaches 1) I will give them the biggest bounty I can offer. =D

So will many mathematicians... :P

Related: http://codegolf.stackexchange.com/q/12177/3808

This is only conjecture, but I suspect that rule 2 is a mathematical fact rather than just a challenge restriction.

"You must take a number n as input, and output out all the Super Collatz numbers up to n" So if I understand this correctly you do NOT ask to output the first n super collatz number? Because that's what the Pyth answer does for example, so I think it's not clear enough.

@Fatalize Yes, that's correct. I'll make that a little more clear in the post.

What? No answer with a Mathematica built in?

Pyth, 23 bytes
q#eol.u@,/N2h*N3NN)STSQ

Demonstration
This works by taking the max of the range up to each number by their Collatz stopping distance, and checking whether that max is the number in question.

Python 2, 104 bytes
c=lambda x:x>1and 1+c([x/2,x*3+1][x%2])
lambda n:[1]+[x for x in range(2,n)if c(x)>max(map(c,range(x)))]

c is a helper function that calculates the Collatz distance for a given integer. The unnamed lambda is the main function, which computes the super Collatz numbers up to (but not including) the input.

Dyalog APL, 41 bytes
(∪⊢⍳⌈\)≢∘{1=⍵:⍬⋄2|⊃⌽⍵:⍵,∇1+3×⍵⋄⍵,∇⍵÷2}¨∘⍳

An unnamed function. Name or parenthesize to apply.
Test cases:
       ((∪⊢⍳⌈\)≢∘{1=⍵:⍬ ⋄ 2|⊃⌽⍵:⍵,∇ 1+3×⍵ ⋄ ⍵,∇ ⍵÷2}¨∘⍳)¨4 50 10000
┌─────┬────────────────────┬───────────────────────────────────────────────────────────────────────────────────────────┐
│1 2 3│1 2 3 6 7 9 18 25 27│1 2 3 6 7 9 18 25 27 54 73 97 129 171 231 313 327 649 703 871 1161 2223 2463 2919 3711 6171│
└─────┴────────────────────┴───────────────────────────────────────────────────────────────────────────────────────────┘

0 results in undefined behaviour.

Haskell, 84 bytes
c 1=0;c x|odd x=1+c(3*x+1)|0<1=1+c(div x 2)
f x=[n|n<-[1..x],all(c n>)$c<$>[1..n-1]]

This is massively slow, of course, but it works!

ES6, 86 83 bytes
n=>(i=m=0,c=n=>n<3?n:c(n&1?n*3+1:n/2)+1,[for(x of Array(n))if(c(++i)>m&&(m=c(i)))i])

Edit: Saved 3 bytes by switching from filter to an array comprehension.

Oracle SQL 11.2, 329 bytes
WITH q(s,i)AS(SELECT LEVEL s,LEVEL i FROM DUAL CONNECT BY LEVEL<=:1 UNION ALL SELECT s,DECODE(MOD(i,2),0,i/2,i*3+1)i FROM q WHERE i<>1),v AS(SELECT s,COUNT(*)-1 d FROM q GROUP BY s),m AS(SELECT s,d,MAX(d)OVER(ORDER BY s ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)m FROM v)SELECT s FROM m WHERE(d>m OR s=1)AND:1>0ORDER BY 1;

Un-golfed version
WITH q(s,i) AS
  (
    SELECT LEVEL s, LEVEL i
    FROM DUAL CONNECT BY LEVEL <= :1
    UNION ALL
    SELECT q.s, DECODE(MOD(i,2),0,i/2,i*3+1)i FROM q WHERE q.i <> 1
  )
, v AS (SELECT s, COUNT(*)-1 d FROM q GROUP BY s)
, m AS (SELECT s, d, MAX(d)OVER(ORDER BY s ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) m FROM v)
SELECT * FROM m WHERE (d>m OR s=1) AND :1>0
ORDER BY 1;

The q view is a true recursive view (not a hierarchical query with CONNECT BY) that compute all steps toward 1 for every integer between 1 and :1.
The v view compute the stopping distances.
The m view use the analytical version of MAX to apply it to every rows preceding, excluding the current row. That way for each integer we know it's stopping distance and the current greatest stopping distance.
The final query check if the stopping distance is greater than the greatest stopping distance. And adds a few tricks to handle 1 and the special case of :1 having a value of 0.

, 30 chars / 38 bytes
⩥ïⓜМȬ⧺$,a=[])⋎⟮aꝈ-1⟯>ɐ⅋(ɐ=Ⅰ,ᵖ$

Try it here (Firefox only).
The only reason I didn't post this earlier was because I wasn't clear on the specs. Uses a custom encoding that encodes 10-bit chars.
Explanation
⩥ïⓜ creates a range [0,input) to map over. МȬ⧺$,a=[]) generates Collatz numbers in an empty array, and ⋎⟮aꝈ-1⟯>ɐ uses the array of Collatz numbers to get the stopping distance and check if that's greater than the previous maximum stopping distance. If so, ⅋(ɐ=Ⅰ,ᵖ$ makes the current stopping distance the maximum stopping distance and pushes the current item in the range to the stack. After, the stack's items are implicitly printed.

Jelly, 17 bytes
×3‘$HḂ?ƬL$€<Ṫ$PµƇ

Try it online!
I reckon there's still a couple of bytes that can be removed.
How it works
×3‘$HḂ?ƬL$€<Ṫ$PµƇ - Main link. Takes n on the left
               µƇ - Generate the list [1, 2, ..., n] and filter each i based on the following:
         $€       -   Over each j [1, 2, ..., i]:
       Ƭ          -     Do the following until reaching a fixed point:
      ?           -       If statement:
     Ḃ            -         Condition: i is odd
   $              -         If so:
×3                -           Multiply by 3
  ‘               -           Increment
    H             -         Else: Halve
        L         -      Take the length
                      Call this list of lengths l
             $    -   Group the previous two links and run over l
            Ṫ     -     Remove the last value of l
           <      -     Is this greater than each value in l?
              P   -   Is this true for all values?


text:
Interpret the Pig series
Given an input of a Pig,
SickPig,
DeadPig,
QuinePig, or
DeafPig program, choose one of those
"languages" randomly and interpret the input as that "language."
First, randomly choose between one of the five members of the "Pig series":

Pig
If the choice was Pig, mimic the reference
interpreter by doing the following:

Find the first occurrence of the word PIG in the input
(case-sensitive).
If the word PIG does not appear in the input, output the message
File must contain the string 'PIG'. and exit.
Otherwise, split the input string on the first occurrence of PIG.
Output the text after the first occurrence of PIG to a file with a
filename of the text before PIG.
PIG may be contained in the text to be output (so, an input of
fooPIGbarPIGbaz should output barPIGbaz to a file called foo).

Note that the reference interpreter takes input via a command line argument
that specifies a filename to read from. However, your submission may take input in
any of the standard methods accepted on PPCG.
SickPig
If the choice was SickPig, follow the same instructions as Pig. However,
instead of writing the text after PIG to the file, choose randomly from
the following list
GRUNT
MOAN
OINK
BURP
GROAN
WHINE

and output that to the file instead. This random choice must be
independent of the previous choice (so, an output of GRUNT should
have a 1/5 * 1/6 = 1/30 chance overall).
DeadPig
DeadPig is like SickPig, but it always outputs the following string instead
of randomly choosing a string:
Your pig has unfortunately died. Please try again.

QuinePig
QuinePig is like Pig, but instead of writing the text after PIG to the
file, it instead writes the entire input to the file (so, an input of
fooPIGbarPIGbaz should output fooPIGbarPIGbaz to a file called foo).
DeafPig
If the choice was DeafPig, do nothing. (The pig is deaf... what do you
expect?)

Miscellaneous rules:

"Random" means each choice should be roughly equally likely (so, choosing Pig 90% of the time and the other variants only 2.5% of the time is invalid).
You may assume that the requested filenames will always be valid for your
file system (but they may contain spaces, etc.).
For all the variants of Pig, your code may optionally output a single
trailing newline to the file as well.
Since this is code-golf, the shortest code in bytes will win.

+1 what do you expect?

Does the random choice have to be perfectly uniform or is modding 32768 acceptable?

@Dennis Perfect uniformity is not necessary, but each choice must have a roughly equal probability (so mod a big number is okay).

Woah... I wrote that Pig interpreter...

Pyth - 157 bytes
Will be doing string compression.
?}J"PIG"z?=GO[jJtKczJOc"GRUNT MOAN OINK BURP GROAN WHINE"d"Your pig has unfortunately died. Please try again."z0).wGhK.q"File must contain the string 'PIG'."

Doesn't work online cuz of file I/O, but try it outputting [content, filename] to stdio here.

Bash, 251 246 bytes
r=$RANDOM
((r%5<4))||exit
[[ $1 =~ PIG ]]||(echo "File must contain the string 'PIG'.";exit)
s=(GRUNT MOAN OINK BURP GROAN WHINE)
m=("${1#*PIG}" ${s[r%6]}
"Your pig has unfortunately died. Please try again." "$1")
echo -n "${m[r%5]}">"${1%%PIG*}"

This would be a lot shorter if deaf pigs could at least read...

Python 2, 296 286 278 bytes

def g(p):
 import random;f=random.randint;r=f(0,4);i=p.find("PIG")
 if r:
    if i+1:open(p[:i],"w").write([0,p[i+3:],["GRUNT","MOAN","OINK","BURP","GROAN","WHINE"][f(0,5)],"Your pig has unfortunately died. Please try again.",p][r])
    else:print"File must contain the string 'PIG'."

The last two lines start with a tab, instead of the rendered 4 spaces.
Takes input program as function argument.

Hello, when I count the bytes in your submission, I get 317. How are you counting the bytes?

@Ogaday The four spaces preceding the last two lines are actually tab characters. (Stack Exchange replaces tabs with spaces within code blocks, though.)

@Doorknob Ah, ok! That would be it. I wondered why the spaces hadn't been golfed out.

There should be a period after 'PIG'.

@LegionMammal978 Thanks for the hint, complety missed that.

Batch, 409 406 405 bytes
@echo off
set/ar=%random%%%5
if 0==%r% exit/b
set p=x%1
set q=%p:*PIG=%
if %q%==%p% echo File must contain the string 'PIG'.&exit/b
set p=%1
call set p=%%p:PIG%q%=%%
goto %r%
:1
echo %q%>%p%
exit/b
:2
for %%a in (GRUNT.0 MOAN.1 OINK.2 BURP.3 GROAN.4 WHINE.5)do if %%~xa==.%time:~6,1% echo %%~na
exit/b
:3
echo Your pig has unfortunately died. Please try again.>%p%
exit/b
:4
echo %1>%p%

Sadly %p:*PIG=% fails if p is blank, thus the x%1 hack. call set is a nice way to avoid enabledelayedexpansion that I found on Stack Overflow; while the %%~xa==. was a flash of inspiration on my part.
Edit: Saved 3 bytes thanks to @CᴏɴᴏʀO'Bʀɪᴇɴ. Saved 1 byte thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ.

Why @echo on? Isn't that implicitly done? Perhaps you meant @echo off?

Also, for generating a random number, SET/A r=%RANDOM%%%5 is shorter.

@CᴏɴᴏʀO'Bʀɪᴇɴ Ugh, I meant @echo off but I had been debugging... also thanks for the %RANDOM% tip, I hadn't heard of that one.

@CᴏɴᴏʀO'Bʀɪᴇɴ Sadly the %RANDOM% version requires me to use an extra set /a which ends up being 10 bytes longer.

But you're already using set/a...?

Not the second time.