I am practicing with codewars and started doing my first challenge that is about the following:
The set of words is given. Words are joined if the last letter of one word and the first letter of another word are the same. Return true if all words of the set can be combined into one word. Each word can and must be used only once. Otherwise return false.
Input Array of 3 to 7 words of random length. No capital letters.
Example true Set: excavate, endure, desire, screen, theater, excess, night. Millipede: desirE EndurE ExcavatE ExcesS ScreeN NighT Theater.
Example false Set: trade, pole, view, grave, ladder, mushroom, president. Millipede: presidenT Trade.
Here is my code :
public class Millipede {
public static boolean check(String[] millipede) {
boolean itCombines = true;
String setOfWords1 = "";
String setOfWords2 = "";
for (int i = 0; i < millipede.length - 1; i++) {
if (!millipede[i].equals(millipede[i + 1])) {
setOfWords1 = millipede[i];
setOfWords2 = millipede[i + 1];
if (setOfWords1.charAt(setOfWords1.length() - 1) == setOfWords2.charAt(0)) {
return itCombines;
} else {
return !itCombines;
}
}
} return itCombines;
}
}
When I click on the TEST button, everything goes fine and all tests pass, but when I click on the ATTEMPT button it is failing 3 but passing 4.
FAILS:
fiveWords()
screen, desire, theater, excess, night ==> expected: <true> but was: <false>
randomTests()
engine, entertainment, extract, thesis ==> expected: <false> but was: <true>
oneLetterWords()
east, e, e, t, t, e, time ==> expected: <true> but was: <false>
I was trying to use the Random class to get a random index in order to compare Strings in different positions but it was making the test to fail.