Oxaric’s Blog

A compendium of amazing things…

Euler Project Problem #24 Solution

Posted by oxaric on November 24, 2008

It uses C++.


Click to directly download euler-solution-24.cpp

// filename 'euler-solution-24.c'
// By: Louis Casillas, oxaric@gmail.com

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

#include <stdio.h>
#include <stdlib.h>

/**
   Read a number, N, from standard input and print the
   permutations.
 */

int permutation_count = 0;

void print(const int *v, const int size)
{
   permutation_count++;

   if ( permutation_count == 1000000 )
   {
      printf( "\nThe millionth permutation is: " );

       for (int i = 0; i < size; i++) {
         printf("%4d", v[i] );
       }
       printf("\n");

      exit(0);      
   }

} // print

void swap(int *v, const int i, const int j)
{
  int t;
  t = v[i];
  v[i] = v[j];
  v[j] = t;
} 

void rotateLeft(int *v, const int start, const int n)
{
  int tmp = v[start];
  for (int i = start; i < n-1; i++) {
    v[i] = v[i+1];
  }
  v[n-1] = tmp;
} // rotateLeft

void permute(int *v, const int start, const int n)
{
  print(v, n);
  if (start < n) {
    int i, j;
    for (= n-2; i >= start; i--) {
      for (= i + 1; j < n; j++) {
   swap(v, i, j);
   permute(v, i+1, n);
      } // for j
      rotateLeft(v, i, n);
    } // for i
  }
} // permute

void init(int *v, int N)
{
  for (int i = 0; i < N; i++) {
    v[i] = i;
  }
} // init

int main()
{
  char buf[80];
  int N = 10;

    int *= new int[N];
    init(v, N);
    permute(v, 0, N);
    delete [] v;

   return 0;
}

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>