Guest User

Untitled

a guest
Jul 15th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. import java.util.concurrent.ExecutorService;
  2. import java.util.concurrent.Executors;
  3. import java.util.concurrent.TimeUnit;
  4. import java.util.concurrent.atomic.AtomicLong;
  5.  
  6. public class Queens implements Runnable {
  7. private static final int defaultN = 5;
  8. private static volatile int n;
  9. private static AtomicLong count = new AtomicLong(0);
  10.  
  11. public class Generator implements Runnable {
  12. private char[] x;
  13.  
  14. public Generator(char k) {
  15. x = new char[n];
  16. x[0] = k;
  17. }
  18.  
  19. void generate(int k) {
  20. for (char y = 1; y <= n; y++) {
  21. char q = 0;
  22. while (q < k && y != x[q] && Math.abs(k - q) != Math.abs(y - x[q]))
  23. q++;
  24. if (q == k) {
  25. x[k] = y;
  26. if (k == n - 1) {
  27. /*StringBuilder arr = new StringBuilder("");
  28. for (char i = 0; i < n; i++)
  29. arr.append((int) x[i] + " ");
  30. System.out.println(arr.toString());*/
  31. synchronized (count) {
  32. count.getAndIncrement();
  33. }
  34. } else
  35. generate(k + 1);
  36. }
  37. }
  38. }
  39.  
  40. public void run() {
  41. generate(1);
  42. }
  43. }
  44.  
  45. public static void main(String[] args) {
  46. try {
  47. n = Integer.parseInt(args[0]);
  48. if (args.length != 1 || n > 20 || n < 0)
  49. throw new Exception();
  50. } catch (Exception e) {
  51. System.err.println("Usage: Queens n");
  52. System.err.println("Default value of n(" + defaultN + ") used");
  53. n = defaultN;
  54. } finally {
  55. new Thread(new Queens()).start();
  56. }
  57. }
  58.  
  59. public long solve(int newN) throws InterruptedException {
  60. n = newN;
  61. int processors = Runtime.getRuntime().availableProcessors();
  62. ExecutorService pool = Executors.newFixedThreadPool(processors);
  63. for (char i = 1; i <= n; i++) {
  64. pool.execute(new Generator(i));
  65. }
  66. pool.shutdown();
  67. if(pool.awaitTermination(20, TimeUnit.MINUTES)) {
  68. return count.get();
  69. } else {
  70. throw new InterruptedException("Time Limit Exceeded");
  71. }
  72. }
  73.  
  74. public void run() {
  75. long start = System.currentTimeMillis();
  76. System.out.println("----------------------------");
  77. try {
  78. solve(n);
  79. System.out.println("----------------------------");
  80. long stop = System.currentTimeMillis();
  81. System.out.println("Total number of arrangements: " + count);
  82. System.out.println("Time elapsed: " + (stop - start)/1000.0 + " sec.");
  83. } catch (InterruptedException e) {
  84. e.printStackTrace();
  85. System.exit(1);
  86. }
  87. }
  88. }
Add Comment
Please, Sign In to add comment