Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static String getRelationship(Node n1, Node n2) {
- if (n1 == null || n2 == null) {
- return "Does not exist.";
- }
- int aLength = 0;
- int bLength = -1;
- //Length
- //Mark all of n1's ancestors
- Node n = n1;
- while (n != null) {
- n.setMark();
- n = n.parent;
- }
- // check for intersect moving up from n2
- // will unmark ancestor
- boolean haveMetAncestor = false;
- n = n2;
- while (n != null) {
- if (n.mark) {
- bLength++;
- haveMetAncestor = true;
- }
- if (!haveMetAncestor) {
- bLength++;
- } else {
- n.setMark();
- }
- n = n.parent;
- }
- // calculate distance from n1 to intersect, while unmarking.
- n = n1;
- while (n.mark) {
- aLength++;
- n = n.parent;
- }
- while (n != null) {
- n.setMark();
- n = n.parent;
- }
- System.out.println(aLength + " " + bLength);
- //Determine relationship
- String s = n1.data + " is " + n2.data;
- if (aLength == 0) {
- if (bLength == 0) {
- return s;
- } else if (bLength == 1) {
- return s + "'s parent.";
- } else if (bLength == 2) {
- return s + "'s grandparent.";
- } else if (bLength == 3) {
- return s + "'s great grandparent.";
- } else {
- s += "'s ";
- for (int i = 0; i < bLength - 2; i++) {
- s += "great ";
- }
- s += "grandparent";
- return s;
- }
- } else if (aLength == 1) {
- if (bLength == 0) {
- return s + "'s child";
- } else if (bLength == 1) {
- return s + "'s sibling.";
- } else if (bLength == 2) {
- return s + "'s aunt/uncle.";
- } else {
- s += "'s ";
- for (int i = 0; i < bLength - 2; i++) {
- s += "great ";
- }
- s += "aunt/uncle";
- return s;
- }
- } else if (aLength >= 2) {
- if (aLength == 2 && bLength == 0) {
- return s + "'s grandchild";
- }
- if (bLength == 1) {
- s += "'s ";
- for (int i = 0; i < aLength - 2; i++) {
- s += "great ";
- }
- s += "niece/nephew";
- return s;
- } else if (bLength >= 2) {
- return s + "'s " + (Math.min(bLength, aLength) - 1) + "th cousin " + Math.abs(aLength - bLength) + " times removed.";
- }
- if (bLength == 0 && aLength >= 3) {
- s += "'s ";
- for (int i = 0; i < aLength - 2; i++) {
- s += "great ";
- }
- s += "grandchild";
- return s;
- }
- }
- return "";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement