Advertisement
Shanix

Untitled

Mar 2nd, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. public static String getRelationship(Node n1, Node n2) {
  2. if (n1 == null || n2 == null) {
  3. return "Does not exist.";
  4. }
  5.  
  6. int aLength = 0;
  7. int bLength = -1;
  8.  
  9. //Length
  10.  
  11. //Mark all of n1's ancestors
  12. Node n = n1;
  13. while (n != null) {
  14. n.setMark();
  15. n = n.parent;
  16. }
  17.  
  18. // check for intersect moving up from n2
  19. // will unmark ancestor
  20. boolean haveMetAncestor = false;
  21. n = n2;
  22. while (n != null) {
  23. if (n.mark) {
  24. bLength++;
  25. haveMetAncestor = true;
  26. }
  27. if (!haveMetAncestor) {
  28. bLength++;
  29. } else {
  30. n.setMark();
  31. }
  32. n = n.parent;
  33. }
  34.  
  35. // calculate distance from n1 to intersect, while unmarking.
  36. n = n1;
  37. while (n.mark) {
  38. aLength++;
  39. n = n.parent;
  40. }
  41. while (n != null) {
  42. n.setMark();
  43. n = n.parent;
  44. }
  45.  
  46. System.out.println(aLength + " " + bLength);
  47.  
  48. //Determine relationship
  49. String s = n1.data + " is " + n2.data;
  50. if (aLength == 0) {
  51. if (bLength == 0) {
  52. return s;
  53. } else if (bLength == 1) {
  54. return s + "'s parent.";
  55. } else if (bLength == 2) {
  56. return s + "'s grandparent.";
  57. } else if (bLength == 3) {
  58. return s + "'s great grandparent.";
  59. } else {
  60. s += "'s ";
  61. for (int i = 0; i < bLength - 2; i++) {
  62. s += "great ";
  63. }
  64. s += "grandparent";
  65. return s;
  66. }
  67. } else if (aLength == 1) {
  68. if (bLength == 0) {
  69. return s + "'s child";
  70. } else if (bLength == 1) {
  71. return s + "'s sibling.";
  72. } else if (bLength == 2) {
  73. return s + "'s aunt/uncle.";
  74. } else {
  75. s += "'s ";
  76. for (int i = 0; i < bLength - 2; i++) {
  77. s += "great ";
  78. }
  79. s += "aunt/uncle";
  80. return s;
  81. }
  82. } else if (aLength >= 2) {
  83. if (aLength == 2 && bLength == 0) {
  84. return s + "'s grandchild";
  85. }
  86. if (bLength == 1) {
  87. s += "'s ";
  88. for (int i = 0; i < aLength - 2; i++) {
  89. s += "great ";
  90. }
  91. s += "niece/nephew";
  92. return s;
  93. } else if (bLength >= 2) {
  94. return s + "'s " + (Math.min(bLength, aLength) - 1) + "th cousin " + Math.abs(aLength - bLength) + " times removed.";
  95. }
  96. if (bLength == 0 && aLength >= 3) {
  97. s += "'s ";
  98. for (int i = 0; i < aLength - 2; i++) {
  99. s += "great ";
  100. }
  101. s += "grandchild";
  102. return s;
  103. }
  104. }
  105. return "";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement