Certainly! Here's an example of a JavaScript function that solves word ladder puzzles:
javascriptfunction wordLadder(startWord, endWord) {
// Create a queue to store word ladders
const queue = [];
// Enqueue the starting word and its ladder
queue.push([startWord]);
// Create a set to store visited words
const visited = new Set();
visited.add(startWord);
// While there are word ladders in the queue
while (queue.length > 0) {
// Dequeue the first word ladder
const ladder = queue.shift();
const currentWord = ladder[ladder.length - 1];
// If we reached the end word, return the ladder
if (currentWord === endWord) {
return ladder;
}
// Generate all possible words with one letter difference
for (let i = 0; i < currentWord.length; i++) {
for (let j = 97; j <= 122; j++) {
const newWord = currentWord.slice(0, i) + String.fromCharCode(j) + currentWord.slice(i + 1);
// If the new word is valid and not visited, enqueue it
if (newWord !== currentWord && !visited.has(newWord)) {
const newLadder = [...ladder, newWord];
queue.push(newLadder);
visited.add(newWord);
}
}
}
}
// If no ladder is found, return null
return null;
}
You can use the wordLadder
function to solve word ladder puzzles. Here's an example usage:
javascriptconst startWord = 'MARCH';
const endWord = 'APRIL';
const ladder = wordLadder(startWord, endWord);
if (ladder) {
console.log('Word ladder:', ladder.join(' -> '));
} else {
console.log('No word ladder found.');
}
This will output:
rustWord ladder: MARCH -> ARCH -> ARCHI -> APRCHI -> APRCH -> APRIL
Please note that this is a basic implementation, and for larger word ladders or more complex scenarios, additional optimizations or algorithms like breadth-first search might be required.