text:
Make a WaterOverflow
You and a friend are playing a game - who can overflow the most containers? There are n containers numbered 1 to n. Each container has a certain maximum capacity of water, in litres.
You take turns with your friend to pour discrete amounts of water into the containers. On your turn, you may pour 2 litres of water into one container (you can't distribute into multiple containers), and on your friend's turn, he must pour 3 litres. You may also choose, on your turn, to not pour water in any of the containers (you cannot, however, choose to only pour 1 litre). The person who manages to overflow the container - that is, after they finish their turn, the litres of water inside the container is greater than its maximum capacity - gets a point.
The input comes in the form of space separated integers. The leftmost one is labelled 1 and the rightmost one is labelled n. For instance:
Y 2 1 4 3

Note that the letter indicates who goes first. Y means that you go first, and F means that your friend goes first. The 2 litre container is labelled 1, the 1 litre container is labelled 2, etc. So we would call the 2 litre container "Container 1", because it is labelled 1.
Now, your friend has a very naïve strategy. He always pours all his 3 litres of water into the container that is closest to overflowing. If there is more than one container that is equally closest to overflowing, he will pour all his water in the one that is labelled with the lowest number.
Suppose I use the same naïve strategy of pouring all my 2 litres of water into the container that is closest to overflowing. The example input would work out like this:

I pour all my water into Container 2. It overflows, and I get one point.
My friend pours all his water into Container 1. It overflows, and he gets one point.
I pour all my water into Container 4. It now has 2L of water in it, so it needs another 2L to overflow.
My friend pours all his water into Container 4. It overflows, and he gets one point.
I pour all my water into container 3. It now has 2L of water in it, so it needs another 3L to overflow.
My friend pours all his water into Container 3. It overflows, and he gets one point.

Altogether, I only got one point, and my friend got three. That's not good. I can do better than that if I make use of my ability to pass on my turn without pouring water:

I pour all my water into Container 2. It overflows, and I get one point.
My friend pours all his water into Container 1. It overflows, and he gets one point.
I pass.
My friend pours all his water into Container 4. It now has 3L of water in it, so it needs another 1L to overflow.
I pour my water into Container 4. It overflows, and I get one point.
My friend pours all his water into Container 3. It has 3L of water in it now, so it needs another 2L to overflow.
I pour my water into Container 3. It overflows, and I get one point.

By strategically choosing which container to pour my water in, I have managed to obtain 3 points instead of 1. The output format is a list of space separated instructions, where P indicates a pass, and an integer from 1 to n indicates which container I poured water into. For instance, the naïve nonoptimal strategy listed above could be represented as:
2 4 3

Which means I poured into Container 2, then Container 4, then Container 3. The more optimal strategy would be represented as:
2 P 4 3

Which means I poured into Container 2, then passed, then Container 4, then Container 3 (This, by the way, is the output format).
Your program will take in input as described above and return the most optimal solution to get as many points as possible. If there is more than one optimal solution, output either.

Python, 217 202 176
import sys
A=sys.argv[1:]
t=A>["G"]
C=[[int(A[i]),i]for i in range(1,len(A))]
while C:
 c=min(C);d=1.5
 if t:d=c[0]%5<2;print["P",c[1]][d],
 c[0]-=2*d;t^=1
 if[0]>c:C.remove(c)

Reads input from the command line.
Strategy:

If the remaining capacity in the container with the least remaining capacity is congruent 0 or 1 modulo 5, pour 2 litres (it either overflows, or our friend pours 3 more litres into the same container, bringing us back to the same point.)
Otherwise, no move improves our position, so do nothing (note that this isn't necessarily the shortest optimal strategy.)

Wow, 15 minutes before me :(

You can save a few bytes by using ; in stead of multiple lines at the top, as space+newline is more than semi-colon.

Java - 718
To generalize, the optimal amount of water in the bucket at the beginning of my turn should be capacity-1 or full. So the previous turn (ideally) it should have been capacity-4 or capacity-3, and capacity-7 or capacity-6.
So the only option that is bad for me would be capacity - n where n % 3 == 2. So my strategy is to wait until the end, then grab the bucket at the last minute, taking care to keep the bucket level in the "ok range". If all the buckets are in the range, then do nothing!
Because you cannot win when the capacity is 2, I simply ignored it.
I think this could be the optimal solution. It beats the friend 100% of the time when the capacities are greater than 2.
Here is the function (for use in simulator above):
BucketChoice makeMove(){
    ArrayList<Bucket> bucketsNotOk = new ArrayList<Bucket>();
    ArrayList<Bucket> bucketsOk = new ArrayList<Bucket>();
    //sort buckets
    for(Bucket b:buckets){
        if(b.litersLeft() % 3 == 2){bucketsNotOk.add(b);}
        if(b.litersLeft() % 3 == 0){bucketsOk.add(b);}
        if(b.litersLeft() % 3 == 1){bucketsOk.add(b);}
    }
    //first I want to grab any buckets ready for overflowing
    for(Bucket b:bucketsOk){
        if(b.litersLeft()<2){System.out.println(buckets.indexOf(b));return new BucketChoice(b,2);}
    }
    //next change buckets to OK
    for(Bucket b:bucketsNotOk){
        //no use adding water if it is doomed
        if(b.litersLeft()>2){System.out.println(buckets.indexOf(b));
            return new BucketChoice(b,2);
        }
    }
    return new BucketChoice(buckets.get(0),0);
}

golfed...hmmm seems long :(
import java.util.*;class o{List<int[]>b=new ArrayList<int[]>(),r=new ArrayList<int[]>();public o(String[]a){for(int x=1;x<a.length;x++){b.add(new int[]{Integer.valueOf(a[x]),0});}while(b.size()>0){if(a[0].equals("F")){e();}int m=0,n=-1,i=0;for(;i<b.size();i++){int[]g=b.get(i);if(g[0]-g[1]<2){n=i;m=1;g[1]+=2;break;}}for(i=0;i<b.size();i++){int[]g=b.get(i);if((g[0]-g[1])%3==2&&m==0){n=i;g[1]+=2;break;}}for(int[]h:b){if(h[0]-h[1]<0){r.add(h);}}for(int[]h:r){b.remove(h);}if(a[0].equals("Y")){e();}if(n!=-1){System.out.print(n+" ");}else{System.out.print("p ");}}}void e(){int[]r={99999,0};for(int[]i:b){if(i[0]-i[1]<r[0]-r[1]){r=i;}}r[1]+=3;if(r[0]-r[1]<0){b.remove(r);}}public static void main(String[]a){new o(a);}}

Try to reduce your code size, as this is a code golf competition.

Ooooooh... I thought is was just algorithm. Thanks!

No problem. Remember to include the amount of bytes your code is after the language name when you're done.

A Java Simulator
I know there are lazy people out there! Here it is:
To continue, just press any key + enter in the console.
OverflowChallenge:
import java.util.ArrayList;
import java.util.Scanner;

    public class OverflowChallenge {
        ArrayList<Bucket> buckets = new ArrayList<Bucket>();
        int myScore=0,friendScore=0;
        public static void main(String[] args) {
            new OverflowChallenge(args);
        }
        public OverflowChallenge(String[]args){
            for(int x=1;x<args.length;x++){
                buckets.add(new Bucket(Integer.valueOf(args[x])));
            }
            while(buckets.size()>0){
                Scanner s = new Scanner(System.in);
                if(args[0].equals("F")){naivePlayerMove();}

                BucketChoice myMove=null;
                if(buckets.size()>0){myMove = makeMove();}else{System.exit(0);}
                myMove.bucket.addWater(myMove.litersAdded);
                if(myMove.bucket.overflowing){buckets.remove(myMove.bucket);}

                System.out.println("you added "+myMove.litersAdded+" to bucket "+buckets.indexOf(myMove.bucket));
                if(myMove.bucket.overflowing){System.out.println("...and you overflowed it!");}

                if(!args[0].equals("F")){naivePlayerMove();}
                for(Bucket b:buckets){
                    System.out.println("bucket "+buckets.indexOf(b)+" has " + b.litersFilled +"/"+b.capacity);
                }
                System.out.println("friend score = "+friendScore);
                System.out.println("my score = "+myScore);
                s.next();
            }
        }
        BucketChoice makeMove(){
            return new BucketChoice(buckets.get(0),2);
        }
        void naivePlayerMove(){
            Bucket lowestBucket=new Bucket(999999999);
            for(int x=0;x<buckets.size();x++){
                if(buckets.get(x).litersLeft()<lowestBucket.litersLeft()){
                    lowestBucket=buckets.get(x);
                }
            }
            lowestBucket.addWater(3);
            System.out.println("your friend added 3 liters to bucket "+buckets.indexOf(lowestBucket));
            if(lowestBucket.overflowing){
                friendScore++;
                buckets.remove(lowestBucket);
                System.out.println("...and overflowed it!");
            }
        }
}

Bucket:
public class Bucket {
    int capacity,litersFilled;
    boolean overflowing = false;
    public Bucket(int capacity){
        litersFilled=0;
        this.capacity=capacity;
    }
    public int litersLeft(){
        return capacity-litersFilled;
    }
    public void addWater(int liters){
        litersFilled+=liters;
        if(litersFilled>capacity){
            overflowing=true;
        }
    }
}

BucketChoice:
public class BucketChoice {
    public BucketChoice(Bucket myBucket, int liters){
        bucket = myBucket;
        litersAdded = liters;
    }
    public Bucket bucket;
    public int litersAdded;
}

Enjoy!

Hi, if your answer isn't a response to the programming challenge, you probably should make it Community Wiki.

How do you make it a community wiki? I have never done that before (though it is kind of embarrassing to say so).

Huh. Turns out it can't be done manually. We'll just have to wait for a moderator to come over to do it.

Try to reduce your code size, as this is a code golf competition.

If you believe your post should be converted to a community wiki, you may flag it for moderator attention.

By the way, this is just to test your algorithm (though it seems a little late for that now that the best algorithm is obvious).

For future reference, please use the "flag" link below posts if they require moderator attention of any sort. I only found this because it was flagged by someone else a few hours ago. Thanks! (/cc @Lilac)

Relevant meta post: http://meta.codegolf.stackexchange.com/q/2106/14215


text:
Fibonacci domino tiling
There's classic combinatorial result that the number of ways to tile a 2*n strip by 1*2 dominoes is the nth Fibonacci number. You goal is to print all the tilings for a given n, drawn with dashes and vertical lines like these 8 tilings for n=5:
|————
|————

——|——
——|——

|||——
|||——

————|
————|

||——|
||——|

|——||
|——||

——|||
——|||

|||||
|||||

You are to provide a program or named function that take n as input and prints the required output. Fewest bytes wins.
Input
A number n between 1 and 10 inclusive via STDIN or function input.
Output
Print every possible domino tilings of the 2*n strip, drawn horizontally. The tilings may be in any order, but each should appear exactly once. They must be separated by a blank line.
A vertical domino is made of two vertical bars (|) and a horizontal domino is made of two em dashes (—). You may use hyphens (-) in place of em dashes to stay in ASCII.
You can do anything with whitespace as long as the printed output looks the same.

Would an extra linefeed after the last tiling fall under anything with whitespace?

@Dennis Yes, extra blank lines are fine.

I'm really surprised to see so many different approaches to solving the same problem. Did you expect that?

@steveverrill No, I totally did not, and am delighted to see the variety! And yours takes the cake for unexpectedness. I mostly had in mind a Fibonacci-style recursion, as most solutions used I used. I didn't expect filtering to be effective, and to the extent I did, I though it would be filtering strings of —— and | by length like Dennis's, not length-n strings of — and | filtered by — appearing in pairs. And for the latter, I'd expect it to be via regexes or string operations on the produced string, like s.split('——)`, not by an arithmetic approach like yours.

I think "1x2 dominoes" is redundant.

C, 106
Golfed version
f(n){
  for(int i,h=n*2<<n;h--;(i/3|i/3*2)-i||(putchar(i>>h%n&1?45:124),h%n||puts(h%(n*2)?"":"\n")))
    i=h/2/n;
}

Original version
i,j,n;
main(){
  scanf("%d",&n);
  for(i=1<<n;i--;)if((i/3|i/3*2)==i){
    for(j=1<<n;j/=2;)printf("%c",i&j?'-':'|');puts("");
    for(j=1<<n;j/=2;)printf("%c",i&j?'-':'|');puts("\n");
  }
}

How it works
The variable i runs from 1<<n-1 down to 0, producing all possible binary numbers with n digits. 0 encodes for | and 1 encodes for -. We are interested in numbers that contain 1's in pairs. Obviously such numbers are divisible by 3.
When a number is divided by 3, the original number can be recovered by multiplying the result by 2 and adding it to itself (effectively mutliplying by 3.) Most numbers will require a carry, but when the process is carried out on the numbers of interest, no carry is required, so in these cases only, OR can be used instead of addition. This is used to test for the numbers of interest, as they are the only ones where the expression i/3|i/3*2 returns the original value of i. See example below.
1111=15 ---> 0101=5 ---> 1111=15 (valid, 0101|1010==0101+1010)
1001=9  ---> 0011=3 ---> 0111=7 (invalid, 0011|0110 != 0011+0110)
The test value is always equal or less than the original value. As numbers that are not multiples of 3 also return a number less than the original when divided by 3 then multipled by 3, the test gives the desired FALSE on these numbers too.
In the original version a couple of loops in j are used to scan through the bits of i and produce the output. In the golfed version a single for loop is used, in which h runs through all numbers from (n*2)*(1<<n)-1 down to 0. Values of i are generated by h/2/n. The variable j is no longer used, as the equivalent quantity is obtained from h%n. The use of n*2 enables both lines to be printed from the same loop, with some nifty multiplexing in the puts statement to print either one or two newlines at the end of the row.
Note that the meat of this is in the increment position of the for() bracket and therefore gets executed after the i=h/2/h.
Sample output n=6:
$ ./a
6
------
------

----||
----||

--|--|
--|--|

--||--
--||--

--||||
--||||

|----|
|----|

|--|--
|--|--

|--|||
|--|||

||----
||----

||--||
||--||

|||--|
|||--|

||||--
||||--

||||||
||||||

The i/3|i/3*2 trick is ingenious! I didn't expect an arithmetic expression for grammar.

CJam, 33 27 bytes
LN{_'|f+@"——"f++}ri*\;{_N}/

Thanks to @jimmy23013 for golfing off 6 bytes!
Try it online!
Background
This is an iterative implementation of a recursive algorithm:
The possible tilings for n can be obtained by adding a vertical domino to the possible tilings for n - 1 and two horizontal dominos to the possible tilings for n - 2.
This way, the number of tilings for n is the sum of the numbers of tilings for n - 1 and n - 2, i.e., the nth Fibonacci number.
How it works
LN                                " A:= [''] B:= ['\n']                         ";
  {             }ri*              " Repeat int(input()) times:                  ";
   _'|f+                          "   C = copy(B); for T ∊ C: T += '|'          ";
              @                   "   Swap A and B.                             ";
               "——"f+             "   for T ∊ B: T += "——"                      ";
                     +            "   B = C + B                                 ";
                        \;        " Discard A.                                  ";
                          {_N}/   " for T ∊ B: print T, T + '\n'                ";

Example run
$ alias cjam='java -jar cjam-0.6.2.jar'

$ cjam domino.cjam <<< 3
|||
|||

——|
——|

|——
|——

$ for i in {1..10}; do echo $[$(cjam domino.cjam <<< $i | wc -l) / 3]; done1
2
3
5
8
13
21
34
55
89

LNli{_'|f\@"——"f\+2/}*\;{_N}/.

f\ hadn't been implemented in 0.6.2 yet, but I was able to combine our approaches. Thanks!

CJam, 42 37 bytes
3li:L#,{3b"——|"2/f=s}%{,L=},_&{N+_N}/

I've counted the dashes as one byte each since the question allows to replace them with ASCII hyphens.
Try it online.
How it works
To obtain all possible tilings of 2 × L, we iterate over all non-negative integers I < 3L, making even digits in base 3 correspond to horizontal dominos and odd digits to vertical ones.
Since each I has L or less digits in base 3, this generates all possible ways of covering the 2 × L strip. All that's left is to filter out the coverings that are bigger or smaller than 2 × L and print the remaining coverings.
3li:L#,      " Read an integer L from STDIN and push A := [ 0 1 ... (3 ** N - 1) ].       ";
{            " For each integer I in A:                                                   ";
  3b         " Push B, the array of I's base 3 digits.                                    ";
  "——|"2/    " Push S := [ '——' '|' ].                                                    ";
  f=         " Replace each D in B with S[D % 2] (the modulus is implicit).               ";
  s          " Flatten B.                                                                 ";
}%           " Collect the result in an array R.                                          ";
{,L=},       " Filter R so it contains only strings of length L.                          ";
_&           " Intersect R with itself to remove duplicates.                              ";
{N+_N}/      " For each string T in B, push (T . '\n') twice, followed by '\n'.           ";

Example run
$ cjam domino.cjam <<< 3
|——
|——

——|
——|

|||
|||

$ for i in {1..10}; do echo $[$(cjam domino.cjam <<< $i | wc -l) / 3]; done
1
2
3
5
8
13
21
34
55
89

Cool. I'm just wondering why you didn't use base 2 like edc65 instead of base 3. That would have saved you from having duplicates. I assume it's because leading zeroes probably get truncated in the step 3b. Is that right?

@steveverrill: Yes, that's precisely the reason. As it is, leading zeros correspond to no domino at all. But not having duplicates would allow me to replace the three blocks with a single one. I'll have to think about this some more.

@steveverrill: I didn't manage to make base 2 work, but a recursive approach seems to be even shorter.

Haskell, 89 bytes
f(-1)=[]
f 0=[""]
f n=map('|':)(f$n-1)++map("--"++)(f$n-2)
g=unlines.(>>= \x->[x,x,""]).f

f is a function that given a number returns a list of one lines of all the possible Fibonacci tilings of length n  possible. it doesn't matter that it returns one line, because both lines of all tilings are the same.
f works by calling recursively on n-1 and n-2 and adding "|" and "--" (respectively) to the strings.
g is the function that answers the questions. it basically calls f on the input, doubles every string so that it  would show two lines and joins them all by newlines.
example output:
*Main> putStrLn $ g 5
|||||
|||||

|||--
|||--

||--|
||--|

|--||
|--||

|----
|----

--|||
--|||

--|--
--|--

----|
----|

JavaScript (E6) 102
Generate configurations from bit sequences, 0 -> '--' and 1 -> '|'.
F=n=>{
  for(i=0;(j=++i)<2<<n;s.length==1+n&&console.log('\n'+s+s))
    for(s='\n';j>1;j>>=1)s+=j&1?'|':'--';
}

Test In firefox/firebug console
F(5)

Output
|----
|----

--|--
--|--

----|
----|

|||--
|||--

||--|
||--|

|--||
|--||

--|||
--|||

|||||
|||||

Haskell: 109 bytes
This is a translation of the well-known Haskell one-liner for lazily computing the sequence of Fibonacci numbers:
b=map.map.(++)
w=zipWith
z=w(++)
s=["\n"]:["|\n"]:z(b"--"s)(b"|"$tail s)
f=sequence_.map putStrLn.(w z s s!!)

The main sequence of tiling strings, ungolfed:
dominos = [""] : ["|"] : zipWith (++) ("--" `before` dominos) ("|" `before` tail dominos)
    where before = map . map . (++)

And the Fibonacci one-liner for comparison:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

Usage example:
$ ghci fibtile
GHCi, version 7.6.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( fibtile.hs, interpreted )
Ok, modules loaded: Main.
*Main> f 5
----|
----|

--|--
--|--

--|||
--|||

|----
|----

|--||
|--||

||--|
||--|

|||--
|||--

|||||
|||||

*Main>

Cobra - 176
Can't wait till I've finished the Cobra golfing package.
def m(n)
    for t in.f(n),print t+t
def f(n,x='')as String*
    if x.length<n,for i in.f(n,x+'-').toList+.f(n,x+'|').toList,yield i
    else if not'-'in x.replace('--',''),yield x+'\n'

J - 54 char
Function taking n as argument on the right.
0{::(];'--'&,"1@[,'|',"1])&>/@[&0&((1 2$,:)&.>'';,'|')

The main root of this golf is the (];'--'&,"1@[,'|',"1])&>/. This takes a list of tilings of length (N-2) and (N-1), and returns a list of tilings of length (N-1) and N. This is the standard Fibonacci recurrence, à la linear algebra. ]; returns the right list as the new left (as there is no change). '--'&,"1@[ adds -- tiles to the left list, while '|',"1] adds | tiles to the right list, and those together are the new right list.
We iterate that over and over n times (that's the @[&0) and start with the empty tiling and the single tiling of length 1. Then we return the first of the pair with 0{::. Meaning, if we run it zero times, we just return the first i.e. the empty tiling. If we run it n times, we calculate up to the n and (n+1) pair, but discard the latter. It's extra work but less characters.
The (1 2$,:) is something J has to do in order to make the tilings in the lists easily extendable. We make the left starting list be a 1-item list of a 2-row matrix of characters, each row having length 0. The right starting list is the same, but has the rows be of length 1, filled with |. Then, we add the new tiles to each row, and append the lists of matrices when we're joining the two sets of tilings together. It's a simple application of a concept J calls rank: essentially manipulating the dimensionality of its arguments, and implicitly looping when necessary.
   0{::(];'--'&,"1@[,'|',"1])&>/@[&0&((1 2$,:)&.>'';,'|')5
----|
----|

--|--
--|--

--|||
--|||

|----
|----

|--||
|--||

||--|
||--|

|||--
|||--

|||||
|||||

Try it for yourself at tryj.tk.

Python 3: 70 bytes
f=lambda n,s="\n":n>0and f(n-1,"|"+s)==f(n-2,"--"+s)or n or print(s*2)

Recursively builds all possible strings s representing one row of dominos, which are duplicated and printed. Starting s as the newline character makes the blank line happen automatically.
The == between the two calls for f is just to perform both function calls. These usually return None because they just print, and == is one of few operators defined for None.
The ands and ors are to produce the right short-circuiting behavior to reproduce the ifs and elses of the ungolfed code.
Ungolfed:
def f(n,s="\n"):
 if n==-1:pass
 elif n==0: print(s*2)
 else: f(n-1,"|"+s);f(n-2,"--"+s)

Retina, 44 bytes
Note: Retina is younger than this challenge.
+`([-|]*)11(1*#)
$1|1$2$1--$2
1
|
.*?#
$0$0#

Takes input in unary with a trailing newline.
Each line should go to its own file and # should be changed to newline in the file. This is impractical but you can run the code as is as one file with the -s flag, keeping the # markers (and changing the newline to # in the input too). You can change the #'s back to newlines in the output for readability if you wish. E.g.:
> echo 1111# | retina -s fib_tile | tr # '\n'
||||
||||

||--
||--

|--|
|--|

--||
--||

----
----

Method:

Starting from the input we swap every line with two other:
one with the first 1 change to | and one with the first two 1's changed to --. We do this until we have lines with at least two 1's.
When there are only single 1's left we changed those to |'s.
We double each line and add an extra newline to it and we get the desired output.

Trailing newline is fine.

source: Stack Exchange

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

sort: votes


text:
Countdown and recycle
Countdown
Your goal for this code-golf challenge is to count down and meanwhile recycle numbers. Let me explain.
First your application reads a number, either as program argument or using stdin.
Next you'll simply need to count down like this:
10 9 8 7 6 (in descending order)
But wait, there is more!
Recycling
There are situations where we can print every number, but don't list every number, we can do recycling! Let me give a quick example:
Input: 110

Output:   11091081071061051041031021010099... etc
Recycled:  10                        1

We've now still listed all the numbers, 110, 109, 108, but we've recycled a 0 and a 1.
Another example:
Input: 9900

Output:   9900989989897989698959894... etc
Recycled:        9 98

Code-golf challenge

Read a number (argument or stdin)
Output the countdown in descending order while recycling all possible numbers (to stdout or file)
Stop when you reach 1 OR the moment you've recycled 0 to 9 (whatever happens first)

Simple example (until 1 reached):
Input: 15
Output: 15141312110987654321

(Notice the 110 instead of 1110)

More advanced example (all recycled):
Input: 110
Output:   110910810710610510410310210100998979695949392919089887868584838281807978776757473727170696867665646362616059585756554535251504948474645443424140393837363534332313029282726252423221
Recycled:  10                            9                    8                    7                    6                    5                    4                    3                    2

(We've recycled all 0-9)

Related

Its really not related to the "one ring to rule them all" problem at all.

@RoyvanRijn you didn't mention anything about ascending order in your question - if i wouldn't have close vote as duplicate of, I would have on "unclear what you're asking". if the numbers must be in ascending order, then how can 10 (in your second example) can be right at the start of the sequence?

@proudhaskeller doesn't the question specify descending order?  "count down" being understood to mean descending order.

@RoyvanRijn my advice would be to state it explicitly. and still, how can 10 be right at the start if it is in ascending order?

@RoyvanRijn oh i see, I understand the question now.

Roy, I didn't vote to close as a duplicate. But explicitly mentioning related questions supplements the system's auto-guessing of related questions. @Will, of course it's related. Remove the early stopping condition and this question is asking you to implement a specific non-optimal strategy for the "one string to rule them all".

The question has not been open for like a few hours and you have already chosen an answer ? I am pretty sure you are definitely getting a shorter answer than that

Your Quick example starts with 1109108, should be 110109108

@WozzeC 1109108 is correct; its reusing the trailing 10 in the 110 as the leading 10 in 109.

Oh I see, Totally dropped the ball on that one :D

Are functions allowed? I'd assumed that "argument" meant command-line argument, but you don't seem to complain about Will's submission as a function? If that's alright, I'll change my Ruby submission as well to save a few more bytes.

T-SQL - 291 277 267 217 199 191 166 158 153 145 142 128 117
After approaching this in a new way, I managed to get down to 145(142 after a couple minor tweaks), not too shabby. That means I might be able to compete for silver or bronze. ^^
DECLARE @ INT=100;WITH N AS(SELECT 1A UNION ALL SELECT A+1FROM N WHERE A<@)SELECT LEFT(A,LEN(A)-1+A%11)FROM N ORDER BY-A

This doesn't print a list, it selects the results. The question never gave specifics about output, so this should be fine. This still has the same limit of 100 on the input, partly because I'm abusing the fact that every 11th term under 100 loses a character and partly because of the default 100 recursion limit on common table expressions.
DECLARE @ INT=100;

WITH N AS
(
    SELECT 1A
    UNION ALL
    SELECT A+1
    FROM N
    WHERE A<@
)

SELECT LEFT(A,LEN(A)-1+A%11)
FROM N
ORDER BY-A

Haha T-SQL, nice one!

Python 143 147
def t(n):
 p=o='';r=0 # p is previous string, o is output string, r is recycled bitmap
 while n and r<1023: # 1023 is first 10 bits set, meaning all digits have been recycled
    s=`n`;i=-1 # s is the current string representation of n
       # i is from end; negative offsets count backwards in strings
    while p.endswith(s[:i])-1:i-=1 # find common ending with prev; s[:0] is '',
       # which all strings end with
    for j in s[:i]:r|=1<<int(j) # mark off recycled bits
    o+=s[i:];p=s;n-=1 # concatenate output, prepare for next number
 print o # done

First level indent is space, second level is tab char.

Some standard char saves: Put things like p=o='' as optional params to the function; you can use * for and in n and r<1023 or maybe even r<1023*n; while x-1: can shave a space as while~-x. Also, it might be shorter to use a set of digits rather than a bit-mask to store which digits have been used.

Haskell, 154 149 147 145 128 120 119 117 bytes
import Data.List
(r%x)n|n>0&&r<":"=[(r\\t)%(x++(show n\\t))$n-1|t<-tails x,isPrefixOf t$show n]!!0|0<1=x
h=['0'..]%""

adding in the recycling-checking cost a lot of characters... sigh
golfed a bit by remembering what digits weren't recycled yet and stopping when the list is empty. then golfed a bit more by moving to explicit recursion and a few more tricks.
example output:
*Main> h 110
"110910810710610510410310210100998979695949392919089887868584838281807978776757473727170696867665646362616059585756554535251504948474645443424140393837363534332313029282726252423221"

Python 2: 119 117
Marking this as community wiki because it is just a more golfed version of Will's answer.
n=input()
d=s,={''}
exec"t=`n`;i=len(t)\nwhile(s*i)[-i:]!=t[:i]:i-=1\ns+=t[i:];d|=set(t[:i]);n-=len(d)<11;"*n
print s

fantastic!  How does the d=s,={''} work?

You can remove parens from while(len(d)<11)*n: to get a different but still-equivalent expression.

@xnor That wouldn't work for len(d) = 11, n >= 2.

@Will d=s,={''} is equivalent to d={''}; s,={''}. s,={''} uses sequence unpacking, a feature more commonly used in statements such as a, b = (b, a), but you can also use it to extract the only element from a single-element sequence.

@flornquake Oh, my mistake. I think you can still do len(d)%11*n, though looks like it's moot with you using an exec loop.

@Will As background for why this clever trick is efficient, it's ironically longer to make an empty set set() than a single-element set {x}. So, flornquake initializes it with a filler member, and checks if it has all ten digits by seeing if it has eleven elements. Since the empty string needs to be initialized into s, it is made to serve as this filler member, combining these initializations to save chars.

@xnor brilliant :)

@Will Yes, len(d)%11*n would've been nice. :)

Ruby, 145 139 130 bytes
n=gets.to_i
d=*?0..?9
s=''
n.times{|i|j=(t=(n-i).to_s).size;j-=1 while s[-j,j]!=u=t[0,j];d-=u.chars;s=t;$><<t[j..-1];exit if[]==d}

Similar approach to Will's, except I'm not using a bit mask, but a set-like array of unused digits instead. Input is via STDIN.
There's an alternative version using while instead of times but whatever I try, the number of bytes is the same:
n=gets.to_i
d=*?0..?9
s=''
(j=(t=n.to_s).size;j-=1 while s[-j,j]!=u=t[0,j];d-=u.chars;s=t;$><<t[j..-1];exit if[]==d;n-=1)while 0<n

CJam, 80 77 65 57 54 Characters
Probably not at all optimized, but a After a lot of optimizations and debugging here is the direct conversion of my ES6 answer in CJam:
Mr{s:C_,{:H<M_,H->=!_CH@-@}g:T>+:MCT<_O@-+:O,A<Ci(*}h;

Try it online here. The function takes the number as STDIN and outputs the recycled countdown, stopping in between if recycling is complete.
I will try to golf it further.
How it works:
Basic idea is that for each countdown number C, check if the first H digits are equal to the last H digits of the resultant string, where H goes from number of digits in C to 0
Mr                                    "Put an empty string and input on stack";
  { ... }h;                           "Run while top element of stack is true, pop when done";
s:C                                   "Store string value of top stack element in C"
   _,                                 "Put the number of characters in C to stack";
     { ... }g                         "Run while top element of stack is true";
:H<                                   "Store the digit iteration in H and slice C";
   M                                  "M is the final output string in making";
    _,H-                              "Take length of M and reduce H from it";
        >                             "Take that many digits of M from end and..."
         =!_                          "Compare with first H digits of C, negate and copy";
            CH@                       "Put C and H on stack and bring the above result to top of stack";
               -                      "Reduce H if the matched result was false";
                @                     "Bring the matched result on top in order continue or break the loop"
             :T                       "Store top stack element in T after the loop";
               >+:M                   "Take everything but first T digits of C and add it to M and update M";
                   CT<_               "Take first T digits of C and copy them";
                       O@             "Put saved digits on stack, and rotate top three elements";
                         -            "Remove all occurence of first T digits of C from O";
                          +:O         "Add first T digits of C to O and update O";
                             ,A<      "Compare number of saved digits with 10";
                                Ci(   "Decrement integer value of C and put it on stack";
                                   *  "If number of saved digits greater than 9, break loop";

JavaScript ES6, 149 146 characters
Such verbose, much characters, wow.
C=n=>{s=c='';while(n>0&s.length<10){j=1;while(t=(n+'').slice(0,-j++))if(c.endsWith(t)){s+=~s.search(t)?'':t;break}c+=(n--+'').slice(1-j)}return c}

Run it in latest Firefox's Web Console.
After running, it creates a method C which you can use like
C(12)
12110987654321

UPDATE: Sometimes, plain old return is shorter than arrow function closure :)

It shouldn't output what digits were recycled, only the counting down sequence after recycling

Oh! is that ? All his examples were outputting that too.

@proudhaskeller Oh, I output the recycled chars too. Thanks, that'll save me some chars.

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


text:
Minimal Boggle-like Arrangements
Consider how a word could be arranged on an arbitrarily large Boggle grid if the rule about not using the same letter cube more than once is ignored. Also assume that you have an unlimited number of letter cubes (with all letters present), and Qu is just Q.
The word MISSISSIPPI could be arranged using only 6 cubes. Here is one possible arrangement:
 S
MIS
 PP

Starting at the M we repeatedly take any step horizontally, vertically, or diagonally until the entire word is spelled out.
Surprisingly, a longer phrase like AMANAPLANACANALPANAMA also only needs 6 cubes:
MAN
PLC

However, the minimum number of cubes needed for longer, more complex strings is not always obvious.
Challenge
Write a program that takes in a string and arranges it in this Boggle-like fashion such that the minimum number of cubes are used. (The dimensions of the resulting grid and the number of empty cells are irrelevant.)
Assume you have have an unlimited number of cubes for each printable ASCII character except space (hex codes 21 to 7E), since it's used as an empty grid cell. Only printable ASCII strings (without spaces) will be input.
Input should be taken from stdin or the command line. Output should go to stdout (or
closest alternative).
Leading or trailing newlines and spaces in the output are fine (but hopefully there aren't an inordinate amount).
The search space blows up exponentially as the string gets longer, but you are not required to attempt to make your algorithm efficient (though that would be nice :) ). This is code-golf, so the shortest solution in bytes wins.
Example
If the input were Oklahoma! (8 character minimum), these would all be valid outputs because the all have exactly 8 filled grid cells and they follow the (revised) Boggle reading pattern:
Oklaho
   !m

or
  !
Oamo
klh

or
   lkO
  !amo
    h

etc.

This sounds like a tough optimisation problem. I think it would have made a nice code challenge.

I can't edit because there's a pending edit from a low-rep user, but Mississippi has two double-s.

What about case sensitivity?

@proudhaskeller I'm sure the input is case insensitive, because: 1) the input is just any printable ASCII 2) the OP didn't mention otherwise 3) The oklahoma example wouldn't be minimal if the input was case insensitive.

@MartinBüttner I think you meant case sensitive

@Ypnypn Absolutely! (because otherwise my 3rd point would make sense ^^) Thanks ;)

@proudhaskeller Uppercase ans lowercase are distinct for the exact reasons MartinBüttner supplied.

Wow how many replies for suck a simple question :)

Python 342 355 398
R=(-1,0,1)
A=[];b={}
def s(w,x,y):
 if w: # not at the end of the word yet?
  for I in R: # search adjacent squares
   for j in R:
    if I|j: # skip the square we are on
     i=I+x;j+=y;c=b.get((i,j)) # get square in board
     if c==w[0]:s(w[1:],i,j) # square is what we are looking for?
     elif not c:b[i,j]=w[0];s(w[1:],i,j);del b[i,j] # we can set square?
 else:A.append(dict(b)) # all solutions
s(raw_input(),9,9) # run the search
A=min(A,key=len) # A is now the shortest solution
C=sum(map(list,A),[]) # put all board coords together
C=range(min(C),max(C)+1) # find the board biggest square bound
for r in C:print"".join(A.get((c,r)," ") for c in C)

Indent at four spaces is actually a tab character.
AMANAPLANACANALPANAMA:
MC
NA
PL

MISSISSIPPI:
S
SI
PPM

Oklahoma!:
oh
 ma
 ! l
    k
     O

Llanfairpwllgwyngyll is lethal ;)

Looks good now, just really slow :/

You can shorten it a bit by removing import sys and replacing sys.argv[1] with raw_input().

@Calvin'sHobbies thx again, neat tip :)  To get an early out you can just change the elif to elif not c and (not A or len(b)<len(A[-1])): and it runs a lot faster

if "Oklahoma!" is OK input, you could just use input() instead of raw_input().


text:
Mixed Base Conversion
Background
Most people on here should be familiar with several base systems: decimal, binary, hexadecimal, octal. E.g. in the hexadecimal system, the number 1234516 would represent
1*16^4 + 2*16^3 + 3*16^2 + 4*16^1 + 5*16^0

Note that we're usually not expecting the base (here, 16) to change from digit to digit.
A generalisation of these usual positional systems allows you to use a different numerical base for each digit. E.g. if we were alternating between decimal and binary system (starting with base 10 in the least significant digit), the number 190315[2,10] would represent
1*10*2*10*2*10 + 9*2*10*2*10 + 0*10*2*10 + 3*2*10 + 1*10 + 5 = 7675

We denote this base as [2,10]. The right-most base corresponds to the least significant digit. Then you go through the bases (to the left) as you go through the digits (to the left), wrapping around if there are more digits than bases.
For further reading, see Wikipedia.
The Challenge
Write a program or function which, given a list of digits D an input base I and an output base O, converts the integer represented by D from base I to base O. You may take input via STDIN, ARGV or function argument and either return the result or print it to STDOUT.
You may assume:

that the numbers in I and O are all greater than 1.
the I and O are non-empty.
that the input number is valid in the given base (i.e., no digit larger than its base).

D could be empty (representing 0) or could have leading zeroes. Your output should not contain leading zeroes. In particular, a result representing 0 should be returned as an empty list.
You must not use any built-in or 3rd-party base conversion functions.
This is code golf, the shortest answer (in bytes) wins.
Examples
D               I                  O        Result
[1,0,0]         [10]               [2]      [1,1,0,0,1,0,0]
[1,0,0]         [2]                [10]     [4]
[1,9,0,3,1,5]   [2,10]             [10]     [7,6,7,5]
[1,9,0,3,1,5]   [2,10]             [4,3,2]  [2,0,1,1,0,1,3,0,1]
[52,0,0,0,0]    [100,7,24,60,60]   [10]     [3,1,4,4,9,6,0,0]
[0,2,10]        [2,4,8,16]         [42]     [1,0]
[]              [123,456]          [13]     []
[0,0]           [123,456]          [13]     []

May I require an infinite list as a base description, or I have to infinitify it myself?

@JanDvorak You mean if you can expect the base lists to already have a sufficient number of repetitions to cover all digits? No, you'll have to do the wrapping around or repeating yourself.

I assume getting an empty list as a base is UB, but may we assume that list of digits is non-empty? Also, what's the policy on trailing zeroes?

Namely, I don't mind an empty list on input, but I'd like to produce [] if the input is [0]

May I request and produce a list of digits in the reverse order (LSD first)?

I've added some clarification, assuming you meant "leading digits".

@JanDvorak no. MSD first.

Hmmmm, so ⊥⊤ in APL is banned :-(

@Howard yes, algorithmshark was so kind to point out in the sandbox that those exist ;)

Does it matter in which order we read the arrays, i.e., does it have to be D I O or would O I D be OK as well?

@Dennis That's fine, as long you don't change the order within the arrays.

Just to clarify: Output [0] is forbidden since it has leading zeros?

@Dennis yes. I'll clarify that in the post.

CJam, 45
q~_,@m>0@{@(:T+@T*@+}/\;La{\)_@+@@md@@j@+}jp;

Finally I found a good use of j.
How it works
Long ArrayList Block j executes the block which takes an integer as the parameter, and Long j will call this block recursively in the block. It will also store the values returned by the block in an internal array, which is initialized by the array parameter. It will not execute the block if the input is already in the array, and the value in the array is returned instead.
So if I initialize it with an array of an empty array, the empty array will be returned for input 0, and the block will be executed for any other input.
q~_,@m>0@{@(:T+@T*@+}/\;     " See below. Stack: O decoded-D ";
La                           " Initialized the value with input 0 as empty list. ";
{
  \)_@+@@md@@                " See below. Stack: remainder O quotient ";
  j                          " Call this block recursively except when the same quotient has
                               appeared before, which is impossible except the 0.
                               Stack: remainder O returned_list ";
  @+                         " Append the remainder to the list. ";
}j
p;                           " Format and output, and discard O. ";

CJam, 49 48
q~_,@m>0@{@(:T+@T*@+}/\;{\)_@+@@md@@}h;;_{}?]W%`

Input should be O I D.
Examples:
$ while read; do <<<$REPLY ./cjam-0.6.2.jar <(echo 'q~_,@m>0@{@(:T+@T*@+}/\;{\)_@+@@md@@}h;;_{}?]W%`');echo; done
[2] [10] [1 0 0]
[10] [2] [1 0 0]
[10] [2 10] [1 9 0 3 1 5]
[4 3 2] [2 10] [1 9 0 3 1 5]
[10] [100 7 24 60 60] [52 0 0 0 0]
[42] [2 4 8 16] [0 2 10]
[13] [123 456] []
[13] [123 456] [0 0]
[1 1 0 0 1 0 0]
[4]
[7 6 7 5]
[2 0 1 1 0 1 3 0 1]
[3 1 4 4 9 6 0 0]
[1 0]
""
""

How it works
q~           “ Read the input and evaluate. ";
_,@m>        " Rotate I to the right by the length of D. ";
0@{          " For each item in D, with the result initialized to 0: ";
  @(:T+      " Rotate I to the left, and set the original first item to T. ";
  @T*@+      " Calculate result * T + current. ";
}/
\;           " Discard I. ";
{            " Do: ";
  \)_@+      " Rotate O to the right, and get a copy of the original last item. ";
  @@md       " Calculate divmod. ";
  @@         " Move O and the quotient to the top of the stack. ";
}h           " ...while the quotient is not 0. ";
;;           " Discard O and the last 0. ";
_{}?         " If the last item is still 0, discard it. ";
]W%          " Collect into an array and reverse. ";
`            " Turn the array into its string representation. ";

I've got to stop using array rotation just because CJam has it... That _{}? trick is really neat.

@sudo {}e| is the same.

Would you mind adding an explanation for the version using j? :)

@MartinBüttner Done.

CJam, 62 61 59 57 bytes
q~Wf%~UX@{1$*@+\@(+_W=@*@\}/;\;{\(+_W=@\md@@}h;;]W%_0=!>p

Reads the input arrays as [O I D] from STDIN. Try it online.
How it works
q~         " Read from STDIN and evaluate the input. Result: [O I D]                      ";
Wf%~       " Reverse each of the three arrays and dump them on the stack.                 ";
UX@        " Push U (0) and X (1); rotate D on top of both.                               ";
{          " For each N in D:                                                             ";
  1$*      "   N *= X                                                                     ";
  @+       "   U += N                                                                     ";
  \@(+     "   I := I[1:] + I[:1]                                                         ";
  _W=@*    "   X *= I[-1]                                                                 ";
  @\       "   ( U I X ) ↦ ( I U X )                                                      ";
}/         "                                                                              ";
;\;        " Discard I and X.                                                             ";
{          " R := []; Do:                                                                 ";
  \(+      "   O := O[1:] + O[:1]                                                         ";
  _W=@\md  "   R += [U / O[-1]], U %= O[-1]                                               ";
  @@       "   ( O U R[-1] ) ↦ ( R[-1] O U )                                              ";
}/         " While U                                                                      ";
;;]        " Discard U and O.                                                             ";
W%         " Reverse R.                                                                   ";
_0=!>      " Execute R := R[!R[0]:] to remove a potential leading zero.                   ";
p          " Print a string presentation of R.                                            ";

Test cases
$ cjam mixed-base.cjam <<< '[ [2]     [10]             [1 0 0]       ]'
[1 1 0 0 1 0 0]
$ cjam mixed-base.cjam <<< '[ [10]    [2]              [1 0 0]       ]'
[4]
$ cjam mixed-base.cjam <<< '[ [10]    [2 10]           [1 9 0 3 1 5] ]'
[7 6 7 5]
$ cjam mixed-base.cjam <<< '[ [4 3 2] [2 10]           [1 9 0 3 1 5] ]'
[2 0 1 1 0 1 3 0 1]
$ cjam mixed-base.cjam <<< '[ [10]    [100 7 24 60 60] [52 0 0 0 0]  ]'
[3 1 4 4 9 6 0 0]
$ cjam mixed-base.cjam <<< '[ [42]    [2 4 8 16]       [0 2 10]      ]'
[1 0]
$ cjam mixed-base.cjam <<< '[ [13]    [123 456]        []            ]'
""
$ cjam mixed-base.cjam <<< '[ [13]    [123 456]        [0 0]         ]'
""

Note that empty strings and empty arrays are indistinguishable to CJam, so []p prints "".

OMG Never seen a 62 bytes CJam program :D

@Optimizer This is probably my longest CJam submission.

@Challenger5 http://codegolf.stackexchange.com/a/51238/12012

@Dennis That wasn't [tag:code-golf], was it?

@Challenger5 It wasn't, but I doubt a golfed version would be shorter than 200 bytes.

Python 2 - 318
from operator import *
d,i,o=input()
c=len
def p(l):return reduce(mul,l,1)
n=sum(x[1]*p((i[-x[0]%c(i)-1:]+x[0]/c(i)*i)[1:]) for x in enumerate(d[::-1]))
r=[]
j=1
t=[]
k=c(o)
while p(t)*max(o)<=n:t=(o[-j%k-1:]+j/k*o)[1:];j+=1
while j:j-=1;t=(o[-j%k-1:]+j/k*o)[1:];r+=[n/p(t)];n%=p(t)
print (r if r[0] else [])

I messed up the order of the arguments by accident, so I had to reverse them. I will work on the slice-fu to get the lists to work in the other direction later, I already wasted my entire lunch break :p
Fixed

Don't say "waste" ;)

You should be able to golf it down to 286 bytes: https://repl.it/JbIk

@Zacharý This was my first golf I think, I'm sure it can be much shorter than that! Feersum's answer demonstrates that quite well I think. If you want you can edit this answer, but I'm afraid I'm not particularly motivated to improve it.

Python 2 - 122
Very straightforward, didn't manage to find any special golf tricks on this one.
def f(D,I,O):
 n,i,l=0,-len(D),[]
 for d in D:n=n*I[i%len(I)]+d;i+=1
 while n:i-=1;b=O[i%len(O)];l=[n%b]+l;n/=b
 return l

Ungolfed:
def f(D,I,O):
    n = 0
    for i in range(len(D)):
        dn = len(D) - i
        n = n * I[-dn % len(I)] + D[i]
    l = []
    i = 0
    while n:
        i -= 1
        b = O[i%len(O)]
        l = [n%b] + l
        n /= b
    return l

Edit: 116-byte program version thanks to FryAmTheEggman
D,I,O=input()
n,i,l=0,-len(D),[]
for d in D:n=n*I[i%len(I)]+d;i+=1
while n:i-=1;b=O[i%len(O)];l=[n%b]+l;n/=b
print l

This version accepts comma-separated input e.g. [1,9,0,3,1,5], [2,10], [10]

@FryAmTheEggman I'm not sure how it could accept input with quotes but separating the arrays with commas works.

APL, 78
{1↓(⊃1⌷⍺)({t←⍺[(⍴⍺)|⍴⍵]
(⌊0⌷⍵÷t)(t|0⌷⍵),1↓⍵}⍣{0=0⌷⍵}),+/(0,⍵)×⌽×\1,(⍴⍵)⍴⌽⊃0⌷⍺}

Examples:
f←{1↓(⊃1⌷⍺)({t←⍺[(⍴⍺)|⍴⍵]
  (⌊0⌷⍵÷t)(t|0⌷⍵),1↓⍵}⍣{0=0⌷⍵}),+/(0,⍵)×⌽×\1,(⍴⍵)⍴⌽⊃0⌷⍺}
(,10)(,2) f 1 0 0
1 1 0 0 1 0 0
(,2)(,10) f 1 0 0
4
(2 10)(,10) f 1 9 0 3 1 5
7 6 7 5
(2 10)(4 3 2) f 1 9 0 3 1 5
2 0 1 1 0 1 3 0 1
(100 7 24 60 60)(,10) f 52 0 0 0 0
3 1 4 4 9 6 0 0
(2 4 8 16)(,42) f 0 2 10
1 0
(123 456)(,13) f ⍬

⍴(123 456)(,13) f ⍬
0
(123 456)(,13) f 0 0

⍴(123 456)(,13) f 0 0
0

Just for general education – with built-ins: {{⍵↓⍨1⍳⍨×⍵}(99⍴⎕)⊤⍵⊥⍨⎕⍴⍨⍴⍵} takes D as right argument, then asks for I and O.

k2 - 83 74 char
Function taking one argument. This was just a lot better suited for K than J, which is why I'm not using J. It would just be a load of boxing/unboxing garbage, and nobody wants that. This is in the k2 dialect (may require some adaptation to work in the open source implementation Kona), but I'll change this to k4 if I can golf it down shorter there.
{:[#x@:|&~&\~x;|*{x 1}.[{_(x,y!*z;y%*z;1!z)}]/(();+/x*1*\(1-#x)#y;|z);()]}

I will note that I take a stand for pickiness here and say that one item lists have to be input as such. ,2 is a list of one item, that item being the scalar 2. Often scalars and 1-item lists are interchangable, but there is logic in this golf that relies on the assumption of list arguments.
To explain the golf, I'll break it into two parts. F is the golf, L is the main loop that calculates the output. The exact mechanism of the looping is that L is applied to its arguments repeatedly until the second argument is zero, then that result is returned. (This is the .[L]/ part.)
L: {_(x,y!*z;y%*z;1!z)}
F: {:[#x@:|&~&\~x;|*{x 1}.[L]/(();+/x*1*\(1-#x)#y;|z);()]}

By explosion:
{_(x,y!*z;y%*z;1!z)}  /function, args x y z
  (      ;    ;   )   / update each arg as follows:
               1!z    /  new z: rotate z left
            *z        /  head of z (current base digit)
          y%          /  y divided by that
 _                    /  new y: floor of that
     y!*z             /  y modulo head of z
   x,                 /  new x: append that to old x

{:[#x@:|&~&\~x;|*{x 1}.[L]/(();+/x*1*\(1-#x)#y;|z);()]}  /function, args x y z
            ~x                                           /find the 0s in x
          &\                                             /find leading zeros
        &~                                               /indices of digits that aren't
    x@ |                                                 /those items from x, reverse order
    x :                                                  /assign to x
 :[#          ;                                      ]   /if length is 0:
                                                   ()    / return empty list
                                                  ;      /else:
                      .[L]/                              / loop L repeatedly
                 {x 1}                                   / until y = 0
                           (  ;               ;  )       / starting with args:
                            ()                           /  Lx: empty list
                                       1-#x              /  number of input digits, minus 1
                                      (    )#y           /  cyclically extend base leftward
                                   1*\                   /  running product, start at 1
                                 x*                      /  multiply digits by these
                               +/                        /  Ly: sum of the above
                                               |z        /  Lz: out base, reverse order
               |*                                        / first elem of result, reversed

In action:
  {:[#x@:|&~&\~x;|*{x 1}.[{_(x,y!*z;y%*z;1!z)}]/(();+/x*1*\(1-#x)#y;|z);()]}[1 0 0; ,10; ,2]
1 1 0 0 1 0 0
  f:{:[#x@:|&~&\~x;|*{x 1}.[{_(x,y!*z;y%*z;1!z)}]/(();+/x*1*\(1-#x)#y;|z);()]}
  f[1 0 0; ,2; ,10]
,4
  f .' ((1 9 0 3 1 5; 2 10;           ,10)  /f apply each
>       (1 9 0 3 1 5; 2 10;           4 3 2)
>       (52 0 0 0 0;  100 7 24 60 60; ,10)
>       (0 2 10;      2 4 8 16;       ,42)
>       (();          123 456;        ,13)
>       (0 0;         123 456;        ,13))
(7 6 7 5
 2 0 1 1 0 1 3 0 1
 3 1 4 4 9 6 0 0
 1 0
 ()
 ())

Perl 6, 67 bytes
{[R,] [+]([R,](@^a)Z*1,|[\*] |[R,](@^b)xx*).polymod: |[R,](@^c)xx*}

Try it
Expanded:
{  # bare block lambda with placeholder parameters @a,@b,@c

  [R,]    # reduce the following using reverse meta op ｢R｣ combined with ｢,｣ op
          # (shorter than ｢reverse｣)

    [+](  # sum

        [R,](@^a) # reverse of first argument

      Z[*]        # zipped using &infix:<*> with the following

        1,
        |                    # slip the following in (flattens)
          [\*]               # triangle reduce

            |[R,](@^b) xx*   # reverse of second argument repeated infinitely
    )

    .polymod: |[R,](@^c) xx* # moduli the reverse of third argument repeated
}

In case you aren't sure what triangle reduce does:
[\*] 1,2,3,4,5
# 1, 1*2, 1*2*3, 1*2*3*4, 1*2*3*4*5
# 1,   2,     6,      24,       120

If I could take the inputs reversed, and output the reverse, it would be 47 bytes.
{[+](@^a Z*1,|[\*] |@^b xx*).polymod: |@^c xx*}

Try it


text:
String Bit Manipulation- There and Back Again
Your job is to encrypt a string using a number key.
Your program will receive 2 strings: one containing a sequence of characters to encrypt, and another one containing an even amount of digits (1-9, never 0).
The encrypting will work like this:

take the string to be encrypt and decode it to binary (ISO-8859-1)
for every pair of numbers x and y in the number string do:
for every character in the string of zeroes and ones, starting from the first one, if the bit is 0 toggle the xth bit in front of the bit you are reading right now. If the bit is 1, toggle the yth bit in front of the bit you are reading right now. If the bit to be toggled is out of bounds, do not toggle anything.

Other than that:
This is a code golf challenge, shortest code wins. Standard Loopholes apply.
Here's a more graphic explanation of what happens:
inputs: "a", "23"
"a" =BIN> "01100001"
"01100001" //first bit is a 0, get the first number in the key, 2.
 - ^       //toggle the bit 2 steps in front
"01000001" //next bit is 1, get second number in the key, 3.
  -  ^     //toggle the bit 3 steps in front
"01001001" //0 bit, toggle the bit that is 2 steps in front.
   - ^
"01000001" //etc
    - ^
"01000101"
     - ^
"01000111"
      -  ^ //no change, out of bounds.
"01000111"
       -  ^
"01000111"
        -  ^
"01000111" =ASCII> "G"

So: a, 23 = G. Then, running G, 23 should be a because this process is perfectly reversible. To decrypt a string encrypted using key 12438135, reverse the ordering of the pairs, 35814312 and run the encrypted string through a similar program that performs the operations in reverse order (starting at the end, approaching the beginning) using that key. (thanks to Martin Büttner for pointing that out)
Good luck and have fun! (My first challenge, tell me if i missed anything :))

I've reordered and made some minor changes to make this less unclear, but it's still not entirely clear to me what the process is. "Extract the bits of each character": in what encoding? I would guess ISO-8859-1, but you should make that explicit. "Form a long string of zeroes and ones, appending each character" using big-endian? "For every pair of numbers": that is, splitting the number string into two, not advancing for (i=0; i+1 < length; i++)? What does "in front of" mean? And why does the code block only use x and never y?

I guess i wasn't quite clear with the question, I'll edit it now.

I will create a base program now to illustrate what the program should accomplish

Btw, I don't think this process is reversible, because some of the toggles depend on earlier toggles. So the first affected bit will return to what it was before. But once you get there, it will cause the toggling of a different bit than during the encoding. My program below yields n if I feed it G.

You are right. To reverse the process you have to run the program again, but instead of starting at the first bit, start at the last one and work backwards to cancel out the flipped bits. Good catch. I will edit the question when i get back from school.

CJam, 53 bytes
SSl++256b2bl2/{Em<_,E-{_0=P=~_2$=!t1m<}*}fPE>2b256b:c

Reads two lines of input: the string, followed by the key.
Try it online.
For decryption, this code can be used:
SSl++256b2bl2/W%{1m>_,E-{_0=P=~_2$=!t1m>}*Dm>}fPE>2b256b:c

Example run
$ LANG=en_US cjam enc.cjam # First two lines are input.
codegolf
345678
q¼M³)6¯J

How it works
CJam's built-in base conversion discards leading zeros, so we start by prepending two spaces to the input string. Since a space character is [0 0 1 0 0 0 0 0], this prepends 14 zeros to the bit encoding for the input string.
After each transformation, we rotate the array to the left to avoid adding indexes, skipping the extra 14 bytes from the spaces. This way, toggling bits "out of bounds" affects only those 14 bits, which are discarded after the last toggle.
SSl++       " Read one line of input (plaintext) and prepend two spaces. ";
256b2b      " String ↦ byte array ↦ bit array. ";
l2/         " Read one line of input (key) and split it in chunks of length 2. ";
{           " For each digit pair P: ";
  Em<       " Rotate the array 14 places to the left. ";
  _,E-      " Push the arrays length minus 14. ";
  {         " Do the following that many times: ";
    _0=P=~  " Push the digit of P that corresponds to the first bit of the array. ";
    _2$=    " Retrieve the corresponding bit from the array. ";
    !t      " Compute its logical NOT and modify the array at the given position. ";
    1m<     " Rotate the array one place to the left. ";
  }*        " ";
}fP         " ";
E>          " Discard the first 14 bits of the array. ";
2b256b:c    " Bit array ↦ byte array ↦ string. ";

Wow this is pretty cool. Padding the array and discarding out of bounds modifications is quite ingenious. It doesn't really have to be spaces though, right? Its discarded at the end anyways.

Almost any other character would have worked (null bytes, e.g., would accomplish nothing), but S is a convenient shorthand for " ". The only thing that varies the the shift amount.

Ruby, 230 191 181 178 175 173 171 159 bytes
i,n=$*
s=i.gsub(/./){|c|"%08b"%c.ord}
n.scan(/(.)(.)/){s.size.times{|i|s[j=i+(s[i]==?0?$1:$2).to_i]&&s[j]=s[j]==?0??1:?0}}
$><<s.gsub(/.{8}/){|c|c.to_i(2).chr}

It's just a very naive implementation of the spec. Input via command-line arguments, output to STDOUT.
# Read ARGV into i and n
i,n = $*
# Turn each character into a string of eight 0s and 1s using a format string.
s = i.gsub(/./){|c|"%08b"%c.ord}
# For each pair of characters in n
n.scan(/(.)(.)/){
    # For each index into s
    s.size.times{|i|
        # Determine the index that is to be toggled. $1 and $2 refer to the captures
        # of /(.)(.)/.
        j=i+(s[i]==?0?$1:$2).to_i
        # Using short-circuiting, toggle s[j] if it isn't nil.
        s[j]&&s[j]=s[j]==?0??1:?0
    }
}
# Convert each group of 8 characters back to a single character and print
$><<s.gsub(/.{8}/){|c|c.to_i(2).chr}

GolfScript, 45
~2/{\{8{(..2\?3$&!!4$=48-- 2\?@\^\.}do;}%\;}/

This takes arguments from stdin in the form of two strings (e.g. "a""23") and outputs to stdout.
Test it online here

For "codegolf""345678", it produces an incorrect result. With the official interpreter, it just crashes (Rational can't be coerced into Rational for bitwise arithmetic).

JavaScript 243
function E(s,k,d){for (var o="",a=0,b=0;a<s.length;a++,b%=k.length){
var j,i=8,z,n=s.charCodeAt(a),x=parseInt(k.charAt(b++)),y=parseInt(k.charAt(b++))
for (;i--;)j=d?7-i:i,z=j-(n&(1<<j)?y:x),n=z>0?n^=1<<z:n
o+=String.fromCharCode(n)
}return o}

Example:
var s0 = "codegolf";
var k = "5556";
var s1 = E(s0,k);
var s2 = E(s1,k,true);
console.log(s0+"\n"+s1+"\n"+s2)

Output:
codegolf
ekbaakjb
codegolf


text:
Underhanded Bank Account
You are working as a programmer for a bank.
Your task is to write a program that handles the transactions from one bank account to another.
The program should do the following:

Run in an infinite loop waiting for input.
The input consists of 3 numbers: Accountnumber1, Accountnumber2 and x the amount of money. e.g.  999222 777333 500
Check if the account numbers and x are valid.
The input is valid if the account numbers are not the same and exist in your database and if x is greater than zero,
Transfer the money from account1 to account2, but only if account1 has enough money.
Accounts are not allowed to go into the negative.
If everything goes well print something like "Transferred x$ from number1 to number2"
if something goes wrong, for example because the account numbers are invalid, print an error message.
Stop if the input is 0

The database contains the following bank accounts:

999222: 10000.56$
888333:   335.13$
555222:     56.0$
222111:   123.55$
123456:      0.0$

Simple Python 2 example:
account_numbers = ["999222", "888333", "555222", "222111", "123456"]
account_money   = [10000.56,   335.13,     56.0,   123.55,      0.0]

while True:
    #input in the form of: 999222 777333 500
    input = raw_input()

    if input == "0": break

    number1, number2, x = input.split()

    x = float(x)
    if x <= 0:
        print "Invalid request!"
        continue

    if number1 in account_numbers and number2 in account_numbers and number1 != number2:
        index1 = account_numbers.index(number1)
        index2 = account_numbers.index(number2)

        if account_money[index1] >= x:
            account_money[index1] -= x
            account_money[index2] += x
            print "Transferred %.2f$ from %s to %s" % (x, number1, number2)
        else:
            print "Not enough money in account %s!" % (number1)

    else:
        print "Invalid account number(s)!"

TWIST:
Your bank account number is 123456.
You have exactly 0.0$ in your account.
You want to change that by manipulating your program:
The program should do exactly what it is supposed to do, but should also transfer some free money to your account.
You have to be careful though. Your supervisor will look at your code and he won't be pleased if he sees anything suspicious. He knows about the Standard Loop Holes, so don't even try.
Also, the money you give to yourself shouldn't be too much. It would be suspicious if your money increases too quickly. Don't be greedy.
Your code should be as simple and clear as possible, try to avoid heavy obfuscation.
This is a popularity contest, the answer with the most upvotes wins.
Note: Please output the balance of each account at the end of your program, so that we can see how much money you earned with your hard work (simply to show that your program actually did something).
EDIT: To clarify
The challenge is not to write a program that can handle a large database and a lot of transactions.
The challenge is to make the program look like it only does what it is supposed to do, but in reality doesn't.
For example if the input is 999222 777333 500:
Then add, if possible, 500 to account 777333 and subtract 500 from account 999222. You don't have to "steal" the money from those accounts. You can "generate" the money for your account by simply increasing it somehow in your code.How much is up to you, but you can assume that you want to earn at least 0.1$ and max. 10$ for each given input. It would be suspicious if you would suddenly have millions on your account. You don't have to worry about floating point imprecision, but you can use it to increase your money.
Every user plays the role of the supervisor.
If the trick is hard to spot upvote the answer.

What do you mean by free money ?

@Geobits Assume that you want to earn at least 0.1$ per transaction

@Optimizer free money as in you don't actually do something to earn it

Basically, if told to transfer 500$ to account X, I transfer only 499$ to X and the rest ( 1$) in my account ?

I think the fact that you're using floating-point types to store the amount of money in each account is underhanded enough.

I think this would work a lot better with a much larger initial database and either a set of example test input or a program to generate test inputs. We also need to know what the boss is capable of detecting.

@Geobits the input doesn't matter. The only reason to say how much money you made is so that i can see that your program actually did something.

I edited the question, please point out anything that is still unclear

Can you clarify if the free money is supposed to come out of the transactions, A.K.A. salami slicing (like in the movie Office Space), or if the free money is just meant to be added to the account without any source?

@millinon I believe the ultimate goal is to get money in via any method at all, but to do so in such a way that nobody notices the difference. "You don't have to "steal" the money from those accounts. You can "generate" the money for your account by simply increasing it somehow in your code."

I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. http://meta.codegolf.stackexchange.com/a/8326/20469

I've tried to emulate features of real-world large systems here. I use encapsulation and abstraction to handle the different operations to the database, like getting an account balance and transferring money. The code also has a basic test suite for those functions. However, one programmer has taken advantage of recent changes in the project requirements to add $1 to their account with every input. There's even plausible deniability.
# {account number: balance in USD}
ndb = {
    999222: 10000.56,
    888333: 335.13,
    555222: 56.0,
    222111: 123.55,
    123456: 0.0
}

# {hashed account ID: balance in USD}
# (hash the IDs because integer-based hash tables are fast, and a
# bunch of strcmp's would be slow)
# 2014-10-20: phased out alphabetic account IDs for numeric ones
# keeping the old data here because Murphy's Law guarantees we'll
# need it right after it's deleted. -- RJO
odb = {
#   hash('mEYjxG'): 42.0,
#   hash('lDCIqp'): 1337.0,
#   hash('QDxkwD'): 123456.0,
#   hash('jSWlMM'): 0.0,
#   hash('siYWKC'): 20.14
}

def balance(a, db):
    try:
        return db[hash(a)]
    except:
        raise ValueError('no such account:', a)

def credit(a, n, db):
    if n <= 0:
        raise ValueError('invalid amount: ' + str(n))
    try:
        db[hash(a)] += n
    except:
        raise ValueError('no such account:', a)

# 2012-10-20: parameterizing the database ops to handle both
# old and new databases is a pain in the neck. -- RJO

def debit(a, n, db):
    if n <= 0:
        raise ValueError('invalid amount: ' + str(n))
    if balance(a, db) < n:
        raise ValueError('insufficient funds: below ' + str(n))
    try:
        db[hash(a)] -= n
    except:
        raise ValueError('no such account', a)

def transfer(a, b, n, db):
    if a == b:
        raise ValueError('same account', a)
    debit(a, n, db)
    credit(b, n, db)

# 2014-10-20: tests need to be updated with new account IDs, but
# it's Friday afternoon. -- RJO
def test(db):
    # back up database prior to changes
    bdb = db.copy()
    # test database functions
    try:
        # test 'balance'
        account = 'does not exist'
        try:
            bal = balance(account, db)
            assert(db[hash(account)] == bal)
        except ValueError:
            assert(hash(account) not in db)
        # test 'credit'
        account = 'jSWlMM'
        start = balance(account, db)
        delta = 1
        credit(account, delta, db)
        assert(balance(account, db) == start + delta)
        # test 'debit'
        account = 'lDCIqp'
        start = balance(account, db)
        delta = 1337
        try:
            debit(account, delta, db)
            assert(balance(account, db) == start - delta)
        except ValueError:
            assert(balance(account, db) < delta)
        # test 'transfer'
        account1 = 'mEYjxG'
        account2 = 'siYWKC'
        start1 = balance(account1, db)
        start2 = balance(account2, db)
        delta = 123
        try:
            transfer(account1, account2, delta, db)
            assert(balance(account1, db) == start - delta)
            assert(balance(account2, db) == start + delta)
        except ValueError:
            assert(balance(account1, db) < delta)
    except Exception as ex:
        # log errors
        print ex.message
    finally:
        # roll back all changes
        odb.update(bdb)

# interactive transfers
while True:
    # test everything
    test(ndb)
    # get input
    print 'Transfer $N from A to B:'
    line = raw_input('Enter "A B N" or 0: ')
    # check for exit
    if line == '0':
        print 'Exit'
        # print account balances
        for a in ndb:
            print 'Account', a, 'has', balance(a, ndb), '$'
        break
    # parse input
    try:
        a, b, n = line.split()
        a = int(a)
        b = int(b)
        n = float(n)
    except:
        print 'Bad input!'
        continue
    # make transfer
    try:
        transfer(a, b, n, ndb)
        print 'Transferred', n, '$ from account', a, 'to', b
    except ValueError as e:
        print e

And here's a sample run:
Transfer $N from A to B:
Enter "A B N" or 0: 999222 222111 500
Transferred 500.0 $ from account 999222 to 222111

Transfer $N from A to B:
Enter "A B N" or 0: 555222 888333 12
Transferred 12.0 $ from account 555222 to 888333

Transfer $N from A to B:
Enter "A B N" or 0: 222111 555222 14
Transferred 14.0 $ from account 222111 to 555222

Transfer $N from A to B:
Enter "A B N" or 0: 0
Exit
Account 555222 has 58.0 $
Account 123456 has 4.0 $
Account 888333 has 347.13 $
Account 999222 has 9500.56 $
Account 222111 has 609.55 $

Without even looking at the rest of the code I'm guessing it has something to do with odb being an empty dictionary.

Okay, I got it. Since odb is empty but still declared, the final line in your testing procedure doesn't throw an error - it just updates odb silently instead of restoring the pre-testing values to ndb like it should. Because of this, all the testing changes get committed to ndb, and as such, account 123456 (which is the hash of jSWlMM) gets credited one dollar every time the code is run.

And the plausible deniability comes from the Friday afternoon comment in which he could have missed the final odb to chance it to db. However, he slipped up there in that October 20 wasn't Friday at all - in fact, it was Monday and the week had just begun. For that matter, I think this RJO fellow would need a serious code audit for running tests on a production database in the first place, even if he did write them back right afterwards.

@Joe Z Haha, yeah, moving money around "just as a test" is a really bad idea in real code. I was trying to come up with a plausible way to do db[hash('jSWlMM')] += 1. I considered naming a variable jSWlMM and "accidentally" quoting it somehow, but that's much harder to do in Python than PHP (where leaving off the $ sigil turns the variable into an undefined constant, which is then treated as a string literal).

It was fun trying to look through things, though, I'll give you that.

What about this ?
account_numbers = ["999222", "888333", "555222", "222111", "123456"]
account_money   = [10000.56,   335.13,     56.0,   123.55,      0.0]

counting=locals()[locals().keys()[2]]

while True:
    #input in the form of: 999222 777333 500
    input = raw_input()

    if input == "0": break

    counting[-1]+=1
    number1, number2, x = input.split()

    x = float(x)
    if x <= 0:
        print "Invalid request!"
        continue

    if number1 in account_numbers and number2 in account_numbers and number1 != number2:
        index1 = account_numbers.index(number1)
        index2 = account_numbers.index(number2)

        if account_money[index1] >= x:
            account_money[index1] -= x
            account_money[index2] += x
            print "Transferred %.2f$ from %s to %s" % (x, number1, number2)
        else:
            print "Not enough money in account %s!" % (number1)

    else:
        print "Invalid account number(s)!"

for i in range(len(account_numbers)):
    print "Money in account '%s' is %s" % (account_numbers[i], account_money[i])

Test:
999222 222111 500
Transferred 500.00$ from 999222 to 222111
555222 888333 12
Transferred 12.00$ from 555222 to 888333
222111 555222 14
Transferred 14.00$ from 222111 to 555222
0
Money in account '999222' is 9500.56
Money in account '888333' is 347.13
Money in account '555222' is 58.0
Money in account '222111' is 609.55
Money in account '123456' is 3.0

Traceback (most recent call last):
File "test.py", line 12, in
counting[-1]+=1
TypeError: cannot concatenate 'str' and 'int' objects

I also get an error there. This relies on the ordering of a dictionary, which is (as far as I know) undefined behavior in Python.


text:
Draw a range of mountain ranges
Inspired by Fibonacci domino tiling, this problem is about generating ASCII art representing another famous combinatorial sequence.
A n-step mountain diagram is a drawing of a mountain range, using exactly n '/' and n '\' characters, such that characters sketch a continuous curve which never dips below its initial "altitude".  For example,
   /\/\
/\/    \

and
   /\
/\/  \/\

are both 4-step mountain diagrams, but
/\  /\/\
  \/

is not.
Input
The program should accept an integer n from stdin or as the parameter to a function.
Output
Print all n-step mountain diagrams to stdout. The diagrams can be in any order, but should be separated by some sort of whitespace. You can decide if different diagrams will be output horizontally, vertically, etc.
As in the domino tiling problem, you can use whatever whitespace you want. This includes extra newlines before or after the printed output.
Example
Some sample valid outputs for n=3:
Valid output A:
                                        /\
         /\             /\             /  \    /\/\
/\/\/\  /  \/\       /\/  \           /    \  /    \

Valid output B:
   /\
/\/  \

 /\/\
/    \

/\/\/\

  /\
 /  \
/    \

 /\
/  \/\

Valid output C:
  /\
 /  \       /\
/    \   /\/  \
                  /\/\
 /\              /    \
/  \/\   /\/\/\

This is code golf; shortest program (in bytes) wins.

When you say "You can decide if different diagrams will be output horizontally, vertically, etc.", can the mountain ranges themselves be sideways?

The mountain ranges themselves shouldn't be sideways.  The empty skies between peaks add to the challenge, I think.

Can some ranges appear more than once?

@MattNoonan You're right, printing the mountain ranges horizontally was definitely tricky.

@proud-haskeller It should be once each.

Python 2: 151 chars
N=2*input()
for i in range(2**N):
 L=[];c=1;exec"b=i%2;c+=2*b-1;L+=[[' ']*N];L[-1][b-c]='\/'[b];i=i/2*(c>0);"*N
 for x in(c==1)*zip(*L):print"".join(x)

#Output for n=3:

  /\
 /  \
/    \

 /\/\
/    \

   /\
/\/  \

 /\
/  \/\

/\/\/\

Wow, this is a mess.
The first idea is to use the numbers 0 to 2**N-1 to encode all sequences of N up-moves and down-moves in their bits. We read off these bits one by one by repeated %2 and /2, iterated in an exec loop.
We store the running mountain range sideways in a transposed list of strings L. Each time, we generate a new a row of spaces are replace one space in the new row with / or \ depending on whether an up-move or down-move happened.
The index of that space is c spaces from the end, where c is the running height. Doing it from the front would make the mountains upside down. We further shift it by b to align upward and downward moves , getting [b-c]. Starting c at 1 rather than 0 fixes an off-by-one error.
To eliminate cases where c dips below the start value 1, when this happens, we set i to 0, which causes all further moves to be downward, making c become more negative. Then, when we check whether c ended at 1, we also check whether c ever fell below it. We only print the mountain range if c is 1.
To print, we do zip(*L) to transpose the range from vertical to horizontal, and print each joined string. A lot of trouble in this answer came from Python treats strings as immutable, so we worked with them as lists of characters and only joined them into strings for printing.
Thanks to @flornquake for help and improvements.

You'll need to use ' ' instead of " " if you want to loop using exec. :)  Btw, you don't need to escape the backslash.

@flornquake I forgot to write, I did use ' ' and tried replacing the string with quotes with a variable for it. This still gave index out of range: for _ in[0]*N:exec("b=i%2;c+=2*b-1;L+=[[" "]*N];L[-1][b-c]='\\/'[b];i=i//2*(c>0);")

I meant that you need to write exec("b=i%2;c+=2*b-1;L+=[[' ']*N];L[-1][b-c]='\\/'[b];i=i//2*(c>0);"), i.e. the inner quotes have to be different from the outer ones.

@flornquake Wow do I feel silly, I changed one pair of quotes but not the other. Thanks!

APL (88)
{{⍉↑'\/'[1+⍵=1]/⍨¨¯1+2×K=⊂⌽⍳⌈/K←(⍵≠1)++\⍵}¨Z/⍨{(0=+/⍵)∧∧/0≤+\⍵}¨Z←↓⍉¯1+2×(N/2)⊤⍳2*N←2×⍵}

Output for n=3:
      {{⍉↑'\/'[1+⍵=1]/⍨¨¯1+2×K=⊂⌽⍳⌈/K←(⍵≠1)++\⍵}¨Z/⍨{(0=+/⍵)∧∧/0≤+\⍵}¨Z←↓⍉¯1+2×(N/2)⊤⍳2*N←2×⍵}3
 /\/\/\     /\    /\      /\/\     /\
         /\/  \  /  \/\  /    \   /  \
                                 /    \

Explanation:

(N/2)⊤⍳2*N←2×⍵: get a bitfield for each number from 0 to 2^⍵.
Z←↓⍉¯1+2×: multiply by 2 and subtract 1, giving 1 for up and -1 for down. Store a vector of vectors, each vector containing the representation for one number, in Z.
{...}¨Z: for each element of Z:

∧/0≤+\⍵: check that the running sum never falls below 0 (doesn't go below ground level),
(0=+/⍵): and that the total sum is 0 (ends up back at ground level).

{...}¨Z/⍨: select those elements from Z for which that is true. For each of them:

K←(⍵≠1)++\⍵: find the height for each character, and store in K. Raise each \ up one, so that they line up with the /s properly. This makes the ground height 1.
¯1+2×K=⊂⌽⍳⌈/K: for each column, make a list [1..max(K)], and mark the position of the character in that column with 1 and the rest as -1. (Replicating by -1 fills that position with a space.)
'\/'[1+⍵=1]/⍨¨: find the correct character for each column, and replicate it by the list for that column.
⍉↑: turn the result into a matrix and put it right-side-up

Alright, a horizontal one!

Python, 261 241 236 characters
import itertools as I
n=input()
S={}
for q in I.permutations((-1,1)*n):
 s=0;B=[[' ']*n*2 for _ in range(n+2)];o=0
 for i in q:
    B[n-s+(i==-1)][o]=' /\\'[i];s+=i;o+=1
    if s<0:break
 else:
    for l in (B,[])[q in S]:print''.join(l)
 S[q]=1

It starts taking a while for n=5 and up...
$ echo 1 | py mountrange.py

/\

Laxori@Laxori-PC /cygdrive/c/Programmin
$ echo 2 | py mountrange.py

/\/\

 /\
/  \

Laxori@Laxori-PC /cygdrive/c/Programmin
$ echo 3 | py mountrange.py

/\/\/\

   /\
/\/  \

 /\
/  \/\

 /\/\
/    \

  /\
 /  \
/    \

Laxori@Laxori-PC /cygdrive/c/Programmin
$ echo 4 | py mountrange.py

/\/\/\/\

     /\
/\/\/  \

   /\
/\/  \/\

   /\/\
/\/    \

    /\
   /  \
/\/    \

 /\
/  \/\/\

 /\  /\
/  \/  \

 /\/\
/    \/\

 /\/\/\
/      \

    /\
 /\/  \
/      \

  /\
 /  \
/    \/\

  /\
 /  \/\
/      \

  /\/\
 /    \
/      \

   /\
  /  \
 /    \
/      \

JavaScript (ES6) 159 163
Just like my answer for Fibonacci Domino Tiling, I examine all the sequences of n+n bits, with 1 marking a '/' and 0 marking a '\' (just for output, '2' is later added to mark a newline). While building tha ascii pattern I check the balance - same numbers of 0 and 1, and never going below the starting base line - and output what obey the rules.
Output done with 'alert', that is standard for JS codegolf but quite annoying, and maybe against the rules. Using console.log the character count goes to 165.
F=n=>{
  for(i=0;++i<1<<n+n;l||alert((o+'').replace(/,\d?/g,r=>'\\/\n '[r[1]||3])))
    for(p=l=o=[],j=i;l+1&&p++-n-n;j/=2)
      b=j&1,
      l-=1-b-b,
      (o[k=b+n-l]=o[k]||[2])[p]=b;
}

Less golfed
F=n=>{
  m = n+n
  outer:
  for (i=1; i < 1<<m; i+=2)
  {
    o=[]
    l=0;
    p=1;
    for (j = 1; j <1<<m; j+=j,p++)
    {
      if (i&j)
      {
        q=o[n-l]||[]
        q[p]=1;
        o[n-l]=q
        ++l;
      }
      else
      {
        --l;
        if (l<0) continue outer;
        q=o[n-l]||[]
        q[p]=0;
        o[n-l]=q
      }
    }
    if (l==0) console.log(o.join('\n').replace(/,\d?/g,r=>'\\/'[r[1]]||' '));
  }
}

Test in FireFox/FireBug console.
F(4)

Output
   /\
  /  \
 /    \
/      \

  /\/\
 /    \
/      \

    /\
 /\/  \
/      \

    /\
   /  \
/\/    \

  /\
 /  \/\
/      \

 /\/\/\
/      \

   /\/\
/\/    \

 /\  /\
/  \/  \

     /\
/\/\/  \

  /\
 /  \
/    \/\

 /\/\
/    \/\

   /\
/\/  \/\

 /\
/  \/\/\

/\/\/\/\

Curious if there's any particular reason you write -b-b and -n-n instead of -2*b?

@SteveBennett no reason. Sometimes this pattern is shorter, but not this time (for instance: 2*b+1 -> b-~b)

CJam, 84 bytes
q~:Q{Q[XW]*mr1\{\_@+}%_{*}*{(\{_Q\-)S*@2$m0<" /""\\"?+QS*+Q)<\}%);z{N\++}*o}{;}?1}g

Note that this program prints the mountains in an infinite loop so the online interpreter will not help you; invoke at the command line using
java -jar cjam-0.6.2.jar mountain.cjam <<< 5

or to try online use
q~:Q{Q[XW]*mr1\{\_@+}%_{*}*{(\{_Q\-)S*@2$m0<" /""\\"?+QS*+Q)<\}%);z{N\++}*o}{;}?}fZ

and just hit the run button a bunch of times in succession and imagine the output is concatenated.
The basic idea is that we know a mountain range of size Q has Q of each upward and downward transitions.
 Q[XW]*mr                                   #shuffled list of Q 1s and -1s
1        {\_@+}%                            #height map after each transition
                _{*}*                       #if it passes through 0 it's invalid

Then if it's valid we print it, if not we pop it from the stack so it doesn't overflow.
The print routing basically builds each column as Q - height spaces, then the symbol, then enough more spaces to hit Q+1 total characters, and then we transpose and print the lines with newlines between them.
z{N\++}*o                                   #transpose, insert newlines, print

While I was working on this the question got clarified to require that the mountains be printed once each. That will require some rethinking and probably more characters :/

C,179
excluding unnecessary whitespace.
A similar strategy to edc65. I run through all the n*2-bit binary values, considering /=1 and \=0.
I format a single string containing n linebreaks every n*3 characters. As written the string contains 1000 characters, so there is usually a lot of whitespace printed after the mountain. (This can be fixed by adding s[n*n*3]=0 before the puts.) Anyway, this enables me to output the whole mountain with a single puts after checking that it complies with the rules.
I will try converting it to a function and reducing to a single for loop later.
i,n,x,y,q,r;
main(){
  scanf("%d",&n);
  for(i=1<<n*2;i--;){                              //run though all n*2-digit binary numbers
    char s[]={[0 ...999]=32};                      //fill an array with spaces. This syntax is allowed by GCC
    y=n;                                           //start y one square below the grid (note: r is initialised to 0 by default.)
    for(x=n*2;x--;)                                //for each digit of i
      q=i>>x&1,
      y+=q+r-1,                                    //move up if the current and last digit are 0, down if they are 1, and stay on the same line if they are different.
      y<n?s[y*n*3]=10,s[y*n*3+x+1]=92-45*q:(x=0),  //if y is within the grid, put a newline (ASCII 10)at the beginning of the row and write \ or / (ASCII 92 or 47) to the correct square. Otherwise abort the x loop.
      r=q;                                         //store the current bit of i to r as it will be needed on the next iteration
    n-1-y||puts(s);                                //if y is on the bottom row of the grid, output the mountain
  }
}

Output (note the massive amount of whitespace to the right)
$ ./a
4

 /\
/  \/\/\

   /\
/\/  \/\

 /\/\
/    \/\

  /\
 /  \
/    \/\

     /\
/\/\/  \

 /\  /\
/  \/  \

   /\/\
/\/    \

 /\/\/\
/      \

  /\
 /  \/\
/      \

    /\
   /  \
/\/    \

    /\
 /\/  \
/      \

  /\/\
 /    \
/      \

   /\
  /  \
 /    \
/      \

Haskell, 140 bytes
After several attempts failed to be very golfable, I ended up with this Haskell implementation. I'm happy just to be within a factor of 2 of the APL solution!
Golfed solution:
e=' ':e
m=[[]]:[[('/':e):map(' ':)x++('\\':e):y|k<-[0..n],x<-m!!(n-k),y<-m!!k]|n<-[0..]]
f n=putStr$unlines[map(!!(n-k))a|a<-m!!n,k<-[1..n]]

Ungolfed and commented:
The program builds the set of n-step mountain diagrams recursively. Each diagram is represented by a list of infinitely-long strings, representing the mountain drawn sideways followed by spaces extending to infinity. This ensures that all diagrams have the same height, which makes the recursion easier. The mountain printer accepts a parameter which clips the height to a finite value.
import Data.List (transpose)

-- Elementary picture slices, extending to infinity.
empty = ' ' : empty
up    = '/' : empty
down  = '\\': empty

-- A function which draws a mountain picture to stdout, clipping
-- its height to n.
printMtn n = putStr . unlines . reverse . take n . transpose

{-- Combine mountain pictures x and y by

              x
 x # y  ==   / \y

--}
x # y = up : raised x ++ down : y
    where raised = map (' ':)

-- Given two sets X,Y of mountain pictures, compute the set X <> Y of all
-- combined pictures x#y for x in X, y in Y.
xs <> ys = [ x # y | x <- xs, y <- ys ]

-- Compute the (++,<>)-convolution of a list with itself, e.g.:
--   autoConvolve [x0,x1,x2] == (x2 <> x0) ++ (x1 <> x1) ++ (x0 <> x2)
autoConvolve xs = concat $ zipWith (<>) (reverse xs) xs

{--
    mtns is a list whose nth entry is the list of all n-step mountain diagrams.
    It is defined recursively by:
        --  The only 0-step mountain diagram is empty.
        --  Each (n+1)-step diagram can be uniquely drawn as x#y for
            some k-step diagram x and (n-k)-step diagram y.
--}
mtns = [[]] : [autoConvolve (prefix n) | n <- [1..]]
    where prefix n = take n mtns

-- The driver function: apply the height n mountain printer to each
-- n-step mountain diagram.  Whitespace is guaranteed by the order
-- in which the diagrams appear.
test n = mapM_ (printMtn n) $ mtns!!n

Sample usage:
$ ghci mtn3.hs
GHCi, version 7.6.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( mtn3.hs, interpreted )
Ok, modules loaded: Main.
λ> f 3
  /\
 /  \
/    \

 /\/\
/    \

 /\
/  \/\

   /\
/\/  \

/\/\/\
λ>

GolfScript 103 (demo)
2*:§2\?,{2base.,§\-[0]*\+:a 1\{.2*@(.@+@@+}%:l$)\;),-1%{a,,{.l=2$=\a=1$+*' \\/'= }%\;n+}%\1=*l$(\;0>*}/

The program takes an integer parameter tries to render as mountains all binary representations of the numbers from 0 to 2^(n-1). It does not render invalid combinations (ex: the ones that go below level 0).

Husk, 54 bytes
mȯ¶↔T' §zoFz:,mömR' ∫Ẋo±+:_1†o!"/¦">0uf(Λ≥0∫)†?I←IPṘḋ2

Try it online!
Does surprisingly well in this challenge.
Explanation
ḋ2 array [0,1]
Ṙ repeat each \$n\$ times : 3 → [1,1,1,0,0,0]
†?I←I decrement the zeroes
f(Λ≥0∫) filter out the non-ranges using cumulative sum
u uniquify
§zoFz:, apply the following two functions a & b to the above result and zip them together
mömR' ∫Ẋo±+:_1 Function a: convert unequal pairs to 0's and create the required amount of spaces
†o!"/¦">0 Function b: convert 1 to / and -1 to \
These are now joined to create the mountains.
  ↔T' Transpose each mountain, filling with spaces then reverse
mȯ¶   join with newlines
Each mountain is then auto-displayed with newlines.

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