Advertisement
Guest User

Untitled

a guest
Sep 4th, 2015
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. package D2;
  2.  
  3. import java.util.Random;
  4.  
  5. import edu.princeton.cs.algs4.StdOut;
  6. //import edu.princeton.cs.algs4.StdRandom;
  7. import edu.princeton.cs.algs4.Stopwatch;
  8.  
  9.  
  10. public class testQU {
  11.  
  12. private static int[] numbers; //búum til int array numbers sem inniheldur tölurnar sem við ætlum að para saman
  13. static int count; //
  14.  
  15. public static int count()
  16. { return count; }
  17.  
  18. public static boolean connected(int p, int q) // ef ég kalla á þetta þá fæ ég já eru tengt - nei ekki tengd
  19. { return find(p) == find(q); }
  20.  
  21. private static int find(int p)
  22. { // Find component name.
  23. while (p != numbers[p]) p = numbers[p];
  24. return p;
  25. }
  26. public static void union(int p, int q) // tengjum saman tölur
  27. { // Give p and q the same root.
  28. int pRoot = find(p);
  29. int qRoot = find(q);
  30. if (pRoot == qRoot)
  31. return;
  32. numbers[pRoot] = qRoot;
  33. count--;
  34. }
  35. public static int connect(int N)
  36. {
  37. count = N;
  38. numbers = new int[N];
  39.  
  40. for (int i = 0; i < N; i++) // Initialize component id array.
  41. { numbers[i] = i; } ;
  42.  
  43. int cnt = 0;
  44. while( cnt < N )
  45. {
  46. Random rand = new Random();
  47. int i = rand.nextInt(N - 0);
  48. int j = rand.nextInt(N - 0);
  49.  
  50. testQU.connected(i,j); //continue; // Ignore if connected.
  51. testQU.union(i,j); // Combine components
  52. //StdOut.println(i + " " + j); // and print connection. þarf ekki núna
  53. cnt++;
  54. }
  55. return cnt;
  56. }
  57. public static double timeTrial(int N)//tekur tíman á hvað N margar tölur eru að parast
  58. {
  59. //int MAX = 1000000;
  60. //int[] a = new int[N];
  61. //for (int i = 0; i < N; i++)
  62. // a[i] = StdRandom.uniform(-MAX, MAX);
  63.  
  64. Stopwatch timer = new Stopwatch();
  65. int cnt = connect(N);
  66. return timer.elapsedTime();
  67. }
  68.  
  69. public static void main(String[] args) // fáum inn tölu eigum að tvöfalda hana og finna öll möguleg pör.
  70. { //Ath hvað það tekur mikinn tíma.
  71.  
  72. double prev = timeTrial(12);
  73. for (int N = 250; true; N += N)
  74. {
  75. double time = timeTrial(N);
  76. StdOut.printf("%6d %7.1f ", N, time);
  77.  
  78. StdOut.printf("%5.1f\n", time/prev);
  79. prev = time;
  80. }
  81.  
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement