fork(1) download
  1. import java.util.*;
  2. import java.lang.*;
  3.  
  4. class Main
  5. {
  6. private static void printAllStringsOfLength(int len) {
  7. long start = System.nanoTime();
  8. char[] guess = new char[len];
  9. Arrays.fill(guess, 'a');
  10. int totalGuesses = 0;
  11.  
  12. do {
  13. //System.out.println("Current guess: " + new String(guess));
  14. totalGuesses++;
  15. int incrementIndex = guess.length - 1;
  16. while (incrementIndex >= 0) {
  17. guess[incrementIndex]++;
  18. if (guess[incrementIndex] > 'z') {
  19. if (incrementIndex > 0) {
  20. guess[incrementIndex] = 'a';
  21. }
  22. incrementIndex--;
  23. }
  24. else {
  25. break;
  26. }
  27. }
  28.  
  29. } while (guess[0] <= 'z');
  30.  
  31. long time = System.nanoTime() - start;
  32. System.out.printf("printAllStringsOfLength() yook %.3f seconds to generate %,d combinations%n", time / 1e9, totalGuesses);
  33. }
  34.  
  35. private static void alternatePrint(int len) {
  36. long start = System.nanoTime();
  37. int letters = 26;
  38. int count = len;
  39. int totalGuesses = 0;
  40. StringBuilder sb = new StringBuilder(count);
  41. int combinations = (int) Math.pow(letters, count);
  42. for (int i = 0; i < combinations; i++) {
  43. sb.setLength(0);
  44. for (int j = 0, i2 = i; j < count; j++, i2 /= letters)
  45. sb.insert(0, (char) ('a' + i2 % letters));
  46. // System.out.println(sb);
  47. totalGuesses++;
  48. }
  49. long time = System.nanoTime() - start;
  50. System.out.printf("alternatePrint() took %.3f seconds to generate %,d combinations%n", time / 1e9, totalGuesses);
  51. }
  52.  
  53. public static void main(String[] args) {
  54. printAllStringsOfLength(5);
  55. alternatePrint(5);
  56. }
  57. }
Success #stdin #stdout 3.81s 212864KB
stdin
Standard input is empty
stdout
printAllStringsOfLength() yook 0.059 seconds to generate 11,881,376 combinations
alternatePrint() took 3.644 seconds to generate 11,881,376 combinations