Flipping pancakes

Python, 91 90 chars

L=map(int,raw_input().split())
while L:i=L.index(max(L));print-~i,len(L),;L=L[:i:-1]+L[:i]

Flip the biggest pancake to the top, then flip the whole stack. Remove the biggest pancake from the bottom and repeat.

i is the index of the biggest pancake. L=L[:i:-1]+L[:i] flips i+1 pancakes, flips len(L) pancakes, then drops the last pancake.


Ruby 1.9 - 109 88 79 characters

Much more compact version based on Keith's great python solution:

a=$*.map &:to_i;$*.map{p v=a.index(a.max)+1,a.size;a=a[v..-1].reverse+a[0,v-1]}

Original version:

a=$*.map &:to_i
a.size.downto(2){|l|[n=a.index(a[0,l].max)+1,l].map{|v|v>1&&n<l&&p(v);a[0,v]=a[0,v].reverse}}

If you don't care about spurious operations (reversing stacks of size 1, or reversing the same stack twice in a row) you can make it a bit shorter (96 chars):

a=$*.map &:to_i
a.size.downto(2){|l|[a.index(a[0,l].max)+1,l].map{|v|p v;a[0,v]=a[0,v].reverse}}

Takes the unsorted list as command-line args. Example usage:

>pc.rb 4 2 3 1
4
2
3
2

GolfScript, 34 / 21 chars

(Thanks @PeterTaylor for chopping 4 chars off)

~].{,,{1$=}$\}2*${.2$?.p)p.@\-+}/,

Online test

A shorter, 21 character version works for lists with unique items only

~].${.2$?.p)p.@\-+}/,

Online test

Both versions produce sub-optimal solutions.


Explanation for the shorter solution:

~]         # read input from stdin
.$         # produce a sorted copy from lowest to highest
{          # iterate over the sorted list
  .2$?     # grab the index of the element
  .p       # print the index
  )p       # increment and print the index
  .@\-+    # move the element to the front
}/
,          # leave the length of the list on the stack
           # this flips the reverse sorted list to become sorted

This uses a different algorithm to most of the others posted. Basically it grabs the smallest element of the list, and with two flips moves it to the front, preserving the other elements' order.

To move the nth element to the front:

1 2 3 4 5 6 7   # let's move the 3rd (0-based) element to the front
# flip the first 3 elements
3 2 1 4 5 6 7
# flip the first 3+1 elements
4 1 2 3 5 6 7

It repeats this operation for each element in order, and ends up with a reverse sorted list. It then flips the whole list to leave it fully sorted.


In fact the algorithm is a variation of a 90-char Python solution (my own, of course):

d=map(int,raw_input().split());i=0
while d:n=d.index(max(d));d.pop(n);print n+i,n-~i,;i+=1