Challenge: Climb the word ladder
Kuda's teacher puts a puzzle on the board every Friday: turn cold into warm, changing one letter at a time, and every step must be a real word.
cold
cord (l became r)
card (o became a)
ward (c became w)
warm (d became m)
The class hands in their answers on paper and the teacher has 40 to mark. Let's help with the checking part.
Your task
Write two functions:
oneLetterApart(a, b)returnstrueif the two words have the same length and differ in exactly one position, otherwisefalse.isLadder(words)returnstrueif every word in the list is one letter apart from the word before it.
oneLetterApart("cold", "cord") // true
oneLetterApart("cold", "warm") // false (4 letters differ)
oneLetterApart("cat", "cat") // false (nothing changed)
oneLetterApart("cat", "cart") // false (different lengths)
isLadder(["cold", "cord", "card", "ward", "warm"]) // true
isLadder(["cold", "cord", "warm"]) // false
isLadder(["kombi"]) // true
isLadder([]) // false
Rules
- Words are in lowercase.
- Swapping letters around does not count:
dogandgoddiffer in two places. - You do not need to check that the words are real words, only the steps.
- A single word is a ladder (there is nothing to break). An empty list is not.
Tips
- In
oneLetterApart, count the differences in a loop:if (a[i] !== b[i]) count++. - Write
oneLetterApartfirst, then use it insideisLadder. Small functions that each do one job are easier to get right. - In
isLadder, start the loop ati = 1so thatwords[i - 1]is always the word before. - You can
return falsefrom inside a loop as soon as you find a bad step.