Advertisement
Guest User

munnipea

a guest
Dec 11th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. Map<String, String> people;
  2.  
  3. Map<String, Integer> rank;
  4.  
  5. public DisjointSubsets() {
  6. people = new HashMap<>();
  7. rank = new HashMap<>();
  8. }
  9.  
  10. public String find(String element) throws IllegalArgumentException {
  11. // TODO
  12. // should throw IllegalArgumentException if the element is not present
  13. if (element == null || element.equals("") || !people.containsKey(element)) {
  14. throw new IllegalArgumentException();
  15. }
  16. String firstParent = people.get(element);
  17. while (!people.get(firstParent).equals(firstParent)) {
  18. firstParent = people.get(firstParent);
  19. }
  20.  
  21. return firstParent;
  22. }
  23.  
  24. // should throw IllegalArgumentException if any of elements is not present
  25. public void union(String element1, String element2) throws IllegalArgumentException {
  26. // TODO
  27. // should throw IllegalArgumentException if any of elements is not present
  28. if (element1 == null || element2 == null || element2.equals("") || element1.equals("") || !people.containsKey(element2) || !people.containsKey(element1)) {
  29. throw new IllegalArgumentException();
  30. }
  31. String x = find(element1);
  32. String y = find(element2);
  33.  
  34. if (find(element1).equals(element2)) {
  35. return;
  36. }
  37. if (rank.get(x) > rank.get(y))
  38. people.put(y, x);
  39. else if (rank.get(x) < rank.get(y))
  40. people.put(x, y);
  41. else {
  42. people.put(x, y);
  43. rank.put(y, rank.get(y) + 1);
  44. }
  45.  
  46. }
  47.  
  48. public void addSubset(String element) throws IllegalArgumentException {
  49. // TODO
  50. // should throw IllegalArgumentException if the element is already present
  51. if (element == null || element.equals("") || people.containsKey(element)) {
  52. throw new IllegalArgumentException();
  53. }
  54. people.put(element, element);
  55. rank.put(element, 0);
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement