Cedric Beust challenged to write a counter function that counts from 1 to max but only returns numbers whose digits don't repeat, also display the biggest jump (in the sequences above, it's 4: 98 -> 102) and display the total count of numbers.

There is a non-brute-force solution that answers question about total count of numbers, but printing of that sequence and counting the "biggest jump" would require iteration. Here is my variant without collections and nearly no memory allocation.
  public static void main(String[] args) {
    long l1 = System.currentTimeMillis();
    int n = 0;
    int max = 0;
    int current = 0;
    for (int i = 1; i < 1000000000; i++) {
      if(checkUniqueDigits(i)) {
        n++;
        if(current>max) {
          max = current;
        }
        current = 0;
      } else {
        current++;
      }
    }
    long l2 = System.currentTimeMillis();
    System.err.println(n);
    System.err.println(max);
    System.err.println((l2-l1)/1000f);
  }

  private static boolean checkUniqueDigits(int i) {
    int m = 0;
    for (; i > 0; i /= 10) {
      int k = 1 << (i % 10);
      if ((m & k) > 0) {
        return false;
      }
      m += k;
    }
    return true;
  }
For max 1,000,000,000 it takes ~144 seconds on my 2.33GHz laptop on Java 6.

It would be interesting to break this into parallel tasks and use Kilim or Doug Lea's fork/join framework to take advantage of multicore CPUs...


Your Option (Login or Post by anonymous)