Pages

Wednesday, September 9, 2009

Euler Problem 43 solution

Time (s): ~0.002
package margusmartseppcode.From_40_to_49;

public class Problem_43 {
 static String perms(int n, String s) {
  int fact[] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800 };
  return perms(n, s, fact);
 }

 static String perms(int n, String s, int fact[]) {
  StringBuilder sb = new StringBuilder();
  StringBuilder s2 = new StringBuilder(s);

  n--;
  for (int i, g, sl = s2.length(); sl > 0; sl--, n = n % (g)) {
   i = (int) Math.floor(n / (g = fact[sl] / sl));
   sb.append(s2.charAt(i));
   s2.deleteCharAt(i);
  }
  return sb.toString();
 }

 static long cint(String nr) {
  return Long.parseLong(nr);
 }

 static boolean check(String s) {
  return cint(s.substring(1, 4)) % 2 == 0
    && cint(s.substring(2, 5)) % 3 == 0;
 }

 public static void main(String[] args) {
  long sum = 0;
  String p = "";

  for (int i = 1; i < 25; i++)
   sum += (check(p = perms(i, "0134") + "952867") ? cint(p) : 0)
     + (check(p = perms(i, "0146") + "357289") ? cint(p) : 0);


  System.out.println(sum);
 }
}

No comments:

Post a Comment