Project Euler

Problem #24

A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:

012   021   102   120   201   210

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

Erlang: Running time = 0.08s
+%factorial

p24()->io:format("~s~n",[string:join(p24(999999,lists:map(fun integer_to_list/1,lists:seq(0,9))),"")]).
p24(_,[])->[];
p24(0,L)->L;
p24(N,S)->
	F=factorial(length(S)-1),
	First=N div F,
	[lists:nth(First+1,S)|p24(N rem F,lists:append(lists:sublist(S,First),lists:sublist(S,First+2,length(S)-First-1)))].

Ruby: Running time = 0.0s
+#factorial

def p24perm(n)
  digitsLeft=(0..9).to_a.map{|i|i.to_s}
  ans=""
  9.times do
    options=factorial(digitsLeft.length-1)
    selection=n/options
    n-=selection*options
    ans+=digitsLeft.delete_at(selection)
  end
  ans+=digitsLeft[0]
end

def p24
  puts p24perm(999999)
end