fork(12) download
  1. import java.util.ArrayList;
  2. import java.util.Random;
  3. import java.util.concurrent.Callable;
  4. import java.util.concurrent.ExecutorService;
  5. import java.util.concurrent.Executors;
  6. import java.util.concurrent.ThreadFactory;
  7.  
  8. class SeedFinder {
  9.  
  10. static class SearchTask implements Callable<Long> {
  11.  
  12. private final char[] goal;
  13. private final long start, step;
  14.  
  15. public SearchTask(final String goal, final long offset, final long step) {
  16. final char[] goalAsArray = goal.toCharArray();
  17. this.goal = new char[goalAsArray.length + 1];
  18. System.arraycopy(goalAsArray, 0, this.goal, 0, goalAsArray.length);
  19. this.start = Long.MIN_VALUE + offset;
  20. this.step = step;
  21. }
  22.  
  23. @Override
  24. public Long call() throws Exception {
  25. final long LIMIT = Long.MAX_VALUE - this.step;
  26. final Random random = new Random();
  27. int position, rnd;
  28. long seed = this.start;
  29.  
  30. while ((Thread.interrupted() == false) && (seed < LIMIT)) {
  31. random.setSeed(seed);
  32. position = 0;
  33. rnd = random.nextInt(27);
  34. while (((rnd == 0) && (this.goal[position] == 0))
  35. || ((char) ('`' + rnd) == this.goal[position])) {
  36. ++position;
  37. if (position == this.goal.length) {
  38. return seed;
  39. }
  40. rnd = random.nextInt(27);
  41. }
  42. seed += this.step;
  43. }
  44.  
  45. throw new Exception("No match found");
  46. }
  47. }
  48.  
  49. public static void main(String[] args) {
  50. final String GOAL = "hello".toLowerCase();
  51. final int NUM_CORES = Runtime.getRuntime().availableProcessors();
  52.  
  53. final ArrayList<SearchTask> tasks = new ArrayList<>(NUM_CORES);
  54. for (int i = 0; i < NUM_CORES; ++i) {
  55. tasks.add(new SearchTask(GOAL, i, NUM_CORES));
  56. }
  57.  
  58. final ExecutorService executor = Executors.newFixedThreadPool(NUM_CORES, new ThreadFactory() {
  59.  
  60. @Override
  61. public Thread newThread(Runnable r) {
  62. final Thread result = new Thread(r);
  63. result.setPriority(Thread.MIN_PRIORITY);
  64. result.setDaemon(false);
  65. return result;
  66. }
  67. });
  68. try {
  69. final Long result = executor.invokeAny(tasks);
  70. System.out.println("Seed for \"" + GOAL + "\" found: " + result);
  71. } catch (Exception ex) {
  72. System.err.println("Calculation failed: " + ex);
  73. } finally {
  74. executor.shutdownNow();
  75. }
  76. }
  77. }
  78.  
Time limit exceeded #stdin #stdout 5s 381632KB
stdin
Standard input is empty
stdout
Standard output is empty