Project Euler > Problem 24 > Lexicographic permutations (Java Solution)

Problem:

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?


Solution:

2783915460


Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
 * Solution to Project Euler problem 24
 * By Nayuki Minase
 * 
 * http://nayuki.eigenstate.org/page/project-euler-solutions
 * https://github.com/nayuki/Project-Euler-solutions
 */


public final class p024 implements EulerSolution {
 
 public static void main(String[] args) {
  System.out.println(new p024().run());
 }
 
 
 public String run() {
  // Initialize
  int[] array = new int[10];
  for (int i = 0; i < array.length; i++)
   array[i] = i;
  
  // Permute
  for (int i = 0; i < 999999; i++) {
   if (!Library.nextPermutation(array))
    throw new AssertionError();
  }
  
  // Format output
  String ans = "";
  for (int i = 0; i < array.length; i++)
   ans += array[i];
  return ans;
 }
 
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact