Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const smallest = new Array(13);
  2.  
  3. const makeSet = (i) => {
  4.   smallest[i] = i;
  5. };
  6.  
  7. const find = (i) => {
  8.   return smallest[i];
  9. };
  10.  
  11. const union = (i, j) => {
  12.   const i_id = find(i);
  13.   const j_id = find(j);
  14.  
  15.   if (i_id === j_id) {
  16.     return
  17.   }
  18.  
  19.   const minimal = Math.min(i_id, j_id);
  20.  
  21.   for (let k = 1; k <= smallest.length; k++) {
  22.     if (smallest[k] === i_id || smallest[k] === j_id) {
  23.       smallest[k] = minimal
  24.     }
  25.   }
  26. };
  27.  
  28. for (let i = 1; i <= 12; i++) {
  29.   makeSet(i)
  30. }
  31.  
  32. union(2, 10)
  33. union(7, 5)
  34. union(6, 1)
  35. union(3, 4)
  36. union(5, 11)
  37. union(7, 8)
  38. union(7, 3)
  39. union(12, 2)
  40. union(9, 6)
  41.  
  42. const print = (i) => console.log(find(i));
  43.  
  44. print(6)
  45. print(3)
  46. print(11)
  47. print(9)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement