How to resolve the algorithm Find common directory path step by step in the Wren programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Find common directory path step by step in the Wren programming language

Table of Contents

Problem Statement

Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths: Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'. If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Find common directory path step by step in the Wren programming language

Source code in the wren programming language

var findCommonDir = Fn.new { |paths, sep|
    var count = paths.count
    if (count == 0) return ""
    if (count == 1) return paths[0]
    var splits = List.filled(count, null)
    for (i in 0...count) splits[i] = paths[i].split(sep)
    var minLen = splits[0].count
    for (i in 1...count) {
        var c = splits[i].count
        if (c < minLen) minLen = c
    }
    if (minLen < 2) return ""
    var common = ""
    for (i in 1...minLen) {
        var dir = splits[0][i]
        for (j in 1...count) {
            if (splits[j][i] != dir) return common
        }
        common = common + sep + dir
    }
    return common
}

var paths = [
    "/home/user1/tmp/coverage/test",
    "/home/user1/tmp/covert/operator",
    "/home/user1/tmp/coven/members"
]
System.write("The common directory path is: ")
System.print(findCommonDir.call(paths, "/"))

  

You may also check:How to resolve the algorithm SEDOLs step by step in the Caché ObjectScript programming language
You may also check:How to resolve the algorithm Fermat numbers step by step in the Arturo programming language
You may also check:How to resolve the algorithm User input/Text step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Find duplicate files step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Return multiple values step by step in the Eiffel programming language