How to resolve the algorithm Word ladder step by step in the Wren programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Word ladder step by step in the Wren programming language

Table of Contents

Problem Statement

Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Word ladder step by step in the Wren programming language

Source code in the wren programming language

import "io" for File
import "/sort" for Find

var words = File.read("unixdict.txt").trim().split("\n")

var oneAway = Fn.new { |a, b|
    var sum = 0
    for (i in 0...a.count) if (a[i] != b[i]) sum = sum + 1
    return sum == 1
}

var wordLadder = Fn.new { |a, b|
    var l = a.count
    var poss = words.where { |w| w.count == l }.toList
    var todo = [[a]]
    while (todo.count > 0) {
        var curr = todo[0]
        todo = todo[1..-1]
        var next = poss.where { |w| oneAway.call(w, curr[-1]) }.toList
        if (Find.first(next, b) != -1) {
            curr.add(b)
            System.print(curr.join(" -> "))
            return
        }
        poss = poss.where { |p| !next.contains(p) }.toList
        for (i in 0...next.count) {
            var temp = curr.toList
            temp.add(next[i])
            todo.add(temp)
        }
    }
    System.print("%(a) into %(b) cannot be done.")
}

var pairs = [
    ["boy", "man"],
    ["girl", "lady"],
    ["john", "jane"],
    ["child", "adult"]
]
for (pair in pairs) wordLadder.call(pair[0], pair[1])

  

You may also check:How to resolve the algorithm MD5 step by step in the Rust programming language
You may also check:How to resolve the algorithm Repeat a string step by step in the Tosh programming language
You may also check:How to resolve the algorithm Use another language to call a function step by step in the Wren programming language
You may also check:How to resolve the algorithm Factorial step by step in the Nial programming language
You may also check:How to resolve the algorithm Jordan-Pólya numbers step by step in the C++ programming language