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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Find common directory path step by step in the Raku 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 Raku programming language

Source code in the raku programming language

my $sep = '/';
my @dirs = 
            /home/user1/tmp/covert/operator
            /home/user1/tmp/coven/members>;

my @comps = @dirs.map: { [ .comb(/ $sep [  . ]* /) ] }; 

my $prefix = '';

while all(@comps[*]»[0]) eq @comps[0][0] {
    $prefix ~= @comps[0][0] // last;
    @comps».shift;
}

say "The longest common path is $prefix";


my $sep := '/';
my @dirs := 
             /home/user1/tmp/covert/operator
             /home/user1/tmp/coven/members>;

my @comps = @dirs.map: { [ .comb(/ $sep [  . ]* /) ] };

say "The longest common path is ",
    gather for 0..* -> $column {
        last unless all(@comps[*]»[$column]) eq @comps[0][$column];
        take @comps[0][$column] // last;
    }


my $sep = '/';
my @dirs = 
            /home/user1/tmp/covert/operator
            /home/user1/tmp/coven/members>;

sub is_common_prefix { so $^prefix eq all(@dirs).substr(0, $prefix.chars) }

say ([\~] @dirs.comb(/ $sep [  . ]* /)).reverse.first: &is_common_prefix


  

You may also check:How to resolve the algorithm Roman numerals/Decode step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm Write to Windows event log step by step in the Rust programming language
You may also check:How to resolve the algorithm Humble numbers step by step in the Racket programming language
You may also check:How to resolve the algorithm Doubly-linked list/Traversal step by step in the PureBasic programming language
You may also check:How to resolve the algorithm Vigenère cipher step by step in the Liberty BASIC programming language