Saturday 11 April 2009

PROJECT EULER #24

Link to 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?

using System;

namespace project_euler
{
class Program
{
static void Main()
{
//Problem 24
//There are 10! permutations of 0123456789
//There are 9! permutations of 123456789 = 362880
//So for numbers beginning with 0 and 1 there are 725760 permutations
//Thus we want the 1000000 - 725760 = 274240. permutation in the 2xxxxxxxxx group.
//20xxxxxxxx has 8! permutations = 40320. 274240/40320 = 6.8....etc
DateTime start = DateTime.Now;
char[] result= new char[10];
double permutation = 1000000;
string s = "0123456789";
for (int i = s.Length-1; i >= 0; i--)
{
double index = Math.Ceiling(permutation/FactorialSmallInt(s.Length-1))-1;
result[i] = s[(int) index];
s=s.Remove((int) index, 1);
permutation -= FactorialSmallInt(i)*index;
}
Array.Reverse(result);
Console.WriteLine(new string(result));
TimeSpan time = DateTime.Now - start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
public static double FactorialSmallInt(int n)
{
int factorial=1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
return factorial;
}
}
}

No comments: