Ok, so I have a program with a part that I need to “Order the words such that the last letter of each item in the list is the first letter of the next item, a sort of chain of words linked together by last and first letters.”
The sample input is dog,elephant,giraffe,rhinoceros,tiger
and the correct output is dog,giraffe,elephant,tiger,rhinoceros
while my output is tiger, rhinoceros, dog, giraffe, elephant.
The comparator is this:
class linkedSort implements Comparator {
//will return 1 for a match
//returns 0 if no match
public int compare(Object t, Object t1) {
char[] charArr1 = t.toString().toCharArray();
char[] charArr2 = t1.toString().toCharArray();
if (charArr1[charArr1.length - 1] == charArr2[0]) {
return -1;
} else {
return 1;
}
}
}
Any help would be much appriciated!!
You cannot solve this with a simple comparator and a sort, because the comparison does not define a total order. A total order is one in which the following four properties hold:
Your order is a not total order. First, it breaks reflexivity: for example, “a” ≤ “a”. Second, it breaks antisymmetry: “ease” ≤ “eve” and “eve” ≤ “ease.” Third, it breaks transitivity: “east” ≤ “tea” and “tea” ≤ “aver”, but “east” ≤ “aver” is false. Finally, it is not total: “east” is not less than “west” and “west” is not less than “east.”
To solve this problem, you will need to approach it differently. As a hint, you may want to think of the problem as a graph where the letters are nodes and the words are edges connecting the start and end letters. Can you find a path in this graph that visits every edge exactly once?
Hope this helps!