Find common directory path: Difference between revisions
Content deleted Content added
Find common directory path in Yabasic |
Thundergnat (talk | contribs) m syntax highlighting fixup automation |
||
Line 17:
{{trans|C}}
<
V pos = 0
L
Line 34:
‘/home/user1/tmp/coverage/test’,
‘/home/user1/tmp/covert/operator’,
‘/home/user1/tmp/coven/members’]))</
{{out}}
Line 42:
=={{header|Ada}}==
<
with Ada.Text_IO; use Ada.Text_IO;
Line 80:
);
end Test_Common_Path;
</syntaxhighlight>
Output:
<pre>
Line 87:
=={{header|Aime}}==
<
{
integer e;
Line 111:
0;
}</
=={{header|ALGOL 68}}==
Line 120:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<
CHAR dir sep = "/"; # Assume POSIX #
Line 177:
);
print((dir name(common prefix(dir list)), new line))
)</
Output:
<pre>
Line 185:
=={{header|Arturo}}==
<
paths: map lst => [split.by:"/" &]
Line 207:
"/home/user1/tmp/covert/operator"
"/home/user1/tmp/coven/members"
]</
{{out}}
Line 214:
=={{header|AutoHotkey}}==
<
Dir2 := "/home/user1/tmp/covert/operator"
Dir3 := "/home/user1/tmp/coven/members"
Line 228:
Else Break
MsgBox, % Result</
Message box shows:
<pre>/home/user1/tmp</pre>
=={{header|AWK}}==
<
# paths[count], where sep is a single-character directory separator.
function common_dir(paths, count, sep, b, c, f, i, j, p) {
Line 273:
a[3] = "/home/user1/tmp/coven/members"
print common_dir(a, 3, "/")
}</
Prints <tt>/home/user1/tmp</tt>.
Line 285:
Also, under FreeBASIC, the <code>pathSep</code> arg to <code>commonPath$</code> could be made optional, or even system-dependent.
<
DATA "/home/user2", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"
Line 336:
commonPath$ = tmpstr1
END IF
END FUNCTION</
=={{header|BASIC256}}==
{{trans|GW-BASIC}}
<
y = "/home/user1/tmp/covert/operator"
z = "/home/user1/tmp/coven/members"
Line 365:
REM Task description says no trailing slash, so...
a = i - 1
print "Common path is '"; left(x, a); "'"</
=={{header|Batch File}}==
<
@echo off
setlocal enabledelayedexpansion
Line 430:
endlocal
exit /b
</syntaxhighlight>
{{out}}
<pre>
Line 437:
=={{header|BBC BASIC}}==
<
path$(1) = "/home/user1/tmp/coverage/test"
Line 455:
NEXT J%
UNTIL I% = 0
= LEFT$(p$(1), O%-1)</
=={{header|C}}==
<
int common_len(const char *const *names, int n, char sep)
Line 491:
return 0;
}</
=={{header|C sharp|C#}}==
<
using System;
using System.Collections.Generic;
Line 559:
}
</syntaxhighlight>
=={{header|C++}}==
<
#include <iostream>
#include <string>
Line 592:
std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ;
return compareString.substr( 0 , found ) ;
}</
Output:
<pre>
Line 599:
=={{header|Clojure}}==
<
(defn common-prefix [sep paths]
Line 612:
["/home/user1/tmp/coverage/test"
"/home/user1/tmp/covert/operator"
"/home/user1/tmp/coven/members"]))</
=={{header|Common Lisp}}==
The strings represent file paths, so instead of treating them as simple strings, this uses the specialized pathname functions, which are more robust and generic.
<
(defun common-directory-path (&rest paths)
(do* ((pathnames (mapcar #'(lambda (path) (cdr (pathname-directory (pathname path)))) paths)) ; convert strings to lists of subdirectories
Line 624:
((null (cdr rem)) (make-pathname :directory (cons :absolute (subseq (first pathnames) 0 pos)))) ; take the common sublists and convert back to a pathname
(setq pos (min pos (mismatch (first rem) (second rem) :test #'string-equal))) )) ; compare two paths
</syntaxhighlight>
Line 633:
=={{header|D}}==
This code uses the std.algorithm.commonPrefix function that finds the common prefix of two ranges.
<
string commonDirPath(in string[] paths, in string sep = "/") pure {
Line 646:
"/home/user1/tmp/coven/members"];
writeln(`The common path is: "`, paths.commonDirPath, '"');
}</
{{out}}
<pre>The common path is: "/home/user1/tmp"</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
<syntaxhighlight lang="delphi">
program Find_common_directory_path;
Line 711:
'/home/user1/tmp/coven/members']));
Readln;
end.</
{{out}}
<pre>/home/user1/tmp</pre>
Line 717:
=={{header|Elixir}}==
{{trans|Ruby}}
<
def common_directory_path(dirs, separator \\ "/") do
dir1 = Enum.min(dirs) |> String.split(separator)
Line 727:
dirs = ~w( /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members )
IO.inspect RC.common_directory_path(dirs)</
{{out}}
Line 735:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( find_common_directory ).
Line 747:
keep_common( Components, Acc ) -> [X || X <- Components, Y <- Acc, X =:= Y].
</syntaxhighlight>
{{out}}
<pre>
Line 755:
=={{header|F_Sharp|F#}}==
<
let (|SeqNode|SeqEmpty|) s =
Line 784:
printfn "The common preffix is: %A" (String.Join("/", (commonPrefix args)))
0</
Output for the given task input
<pre>The common preffix is: "/home/user1/tmp"</pre>
=={{header|Factor}}==
<
[ shorter? ] 2keep ? ;
Line 799:
: common-prefix ( seq separator -- prefix )
[ ] swap '[ _ common-prefix-1 ] map-reduce ;</
( scratchpad ) {
Line 810:
=={{header|FreeBASIC}}==
{{Trans|Visual Basic}}
<
' compile: fbc.exe -s console cdp.bas
Line 875:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>/home/user1/tmp/coverage/test
Line 894:
=={{header|Gambas}}==
<
Dim sFolder As String[] = ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"]
Dim sSame As String
Line 910:
Print Mid(sSame, 1, RInStr(sSame, "/") - 1)
End</
Output:
<pre>
Line 921:
E.g. (<code>/home/user1, /home/user1/foo, /home/user1/bar</code>) should result in <code>/home/user1</code>, not <code>/home</code>.
<
import (
Line 999:
fmt.Println("Common path:", c)
}
}</
=={{header|Groovy}}==
Solution:
<
def pathParts = paths.collect { it.split(delim) }
pathParts.transpose().inject([match:true, commonParts:[]]) { aggregator, part ->
Line 1,010:
aggregator
}.commonParts.join(delim)
}</
Test:
<
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
Line 1,022:
'/home/user1/tmp/covert/test',
'/home/user1/tmp/coven/test',
'/home/user1/tmp/covers/test')</
Output:
Line 1,037:
Note that if the root directory is the common path, this reports the same as no match found (i.e. blank result).
<
110 X$ = "/home/user1/tmp/coverage/test"
Line 1,065:
350 A = L0 - 1
360 P$ = LEFT$(X$, A)
370 PRINT "Common path is '"; P$; "'"</
Output:
Line 1,072:
=={{header|Haskell}}==
<
-- Return the common prefix of two lists.
Line 1,094:
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"
]</
Or, expressed directly in applicative terms:
<
import Data.List.Split (splitOn)
Line 1,117:
, "/home/user1/tmp/covert/operator"
, "/home/user1/tmp/coven/members"
]</
{{Out}}
<pre>/home/user1/tmp</pre>
=={{header|HicEst}}==
<
minLength = MIN( LEN(a), LEN(b), LEN(c) )
Line 1,135:
WRITE(Messagebox, Name) "No common directory for", a, b, c
ENDIF
ENDDO</
=={{header|Icon}} and {{header|Unicon}}==
<
write(lcdsubstr(["/home/user1/tmp/coverage/test","/home/user1/tmp/covert/operator","/home/user1/tmp/coven/members"]))
end
Line 1,157:
if not match(s,x) then fail
return s
end</
=={{header|J}}==
'''Solution:'''
<
getCommonPrefix =: {. ;@{.~ 0 i.~ *./@(="1 {.)
getCommonDirPath=: [: getCommonPrefix parseDirs&></
'''Example:'''
<
getCommonPrefix >paths
/home/user1/tmp/cove
'/' getCommonDirPath paths
/home/user1/tmp/</
'''Note:'''
This alternative formulation of parseDirs provides cross-platform support, without the need to specify the path separator.
<
=={{header|Java}}==
{{works with|Java|1.5+}}
This example is case-sensitive.
<
public static String commonPath(String... paths){
String commonPath = "";
Line 1,218:
System.out.println(commonPath(paths2));
}
}</
Output:
<pre>/home/user1/tmp/
Line 1,225:
A slightly modified version of the previous program, only the method commonPath() is changed.
<
static String commonPath(String... paths){
String commonPath = "";
Line 1,244:
return commonPath;
}
</syntaxhighlight>
=={{header|JavaScript}}==
<
/**
* Given an array of strings, return an array of arrays, containing the
Line 1,293:
console.log(`Common path is: ${commonPath(cdpInput)}`);
</syntaxhighlight>
{{out}}
Line 1,301:
=={{header|jq}}==
<
def maximal_initial_subarray:
(map( .[0] ) | unique) as $u
Line 1,314:
[.[] | split(slash)] | maximal_initial_subarray | join(slash) ;
common_path("/")</
Assuming the above jq program is in a file named common_path.jq and that the file directories.txt contains the three given directory strings quoted with double quotation marks:
<
"home/user1/tmp"</
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
0 < length(ds) || return ""
1 < length(ds) || return String(ds[1])
Line 1,342:
println("Comparing:\n - ", join(test, "\n - "))
println("for their common directory path yields:\n", commonpath(test))</
{{out}}
Line 1,353:
=={{header|Kotlin}}==
<
fun findCommonDirPath(paths: List<String>, separator: Char): String {
Line 1,380:
println("The common directory path of:\n\n$pathsToPrint\n")
println("is '${findCommonDirPath(paths, '/')}'")
}</
{{out}}
Line 1,394:
=={{header|Lasso}}==
<
local(
Line 1,410:
}
stdoutnl(commonpath(#path1, #path2, #path3))</
Output:
Line 1,416:
=={{header|Liberty BASIC}}==
<
path$(2) = "/home/user1/tmp/covert/operator"
path$(3) = "/home/user1/tmp/coven/members"
Line 1,440:
end if
wend
end function</
=={{header|Lingo}}==
<
_player.itemDelimiter = sep
Line 1,461:
end repeat
return pathes[1].item[1..commonCnt]
end</
<
pathes.add("/home/user1/tmp/coverage/test")
pathes.add("/home/user1/tmp/covert/operator")
Line 1,468:
put getCommonPath(pathes, "/")
-- "/home/user1/tmp"</
=={{header|MapBasic}}==
Line 1,474:
Derived from the [https://www.rosettacode.org/wiki/Find_common_directory_path#BASIC BASIC] example above
<
Declare Sub Main
Line 1,539:
PRINT "Common path is " + commonPath(x(), Sep)
End Sub</
=={{header|Maple}}==
<syntaxhighlight lang="maple">
dirpath:=proc(a,b,c)
local dirtemp,dirnew,x;
Line 1,552:
end use;
end proc;
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
[Fold[LongestCommonSubsequence, First[x] , Rest[x]]]
FindCommonDirectory[{"/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}]
->"/home/user1/tmp/"</
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
function lcp = longest_common_dirpath(varargin)
ix = find(varargin{1}=='/');
Line 1,574:
longest_common_dirpath('/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members')
</syntaxhighlight>
{{out}}
Line 1,582:
=={{header|Maxima}}==
<
substring(a, 1, catch(for i thru n do (
if not cequal(charat(a, i), charat(b, i)) then throw(i)), n + 1)))$
Line 1,592:
commonpath(["c:/files/banister.jpg", "c:/files/bank.xls", "c:/files/banana-recipes.txt"]);
"c:/files"</
=={{header|MUMPS}}==
<syntaxhighlight lang="mumps">FCD
NEW D,SEP,EQ,LONG,DONE,I,J,K,RETURN
SET D(1)="/home/user1/tmp/coverage/test"
Line 1,609:
WRITE !,"The longest common directory is: ",RETURN
KILL D,SEP,EQ,LONG,DONE,I,J,K,RETURN
QUIT</
Usage:<pre>
USER>D FCD^ROSETTA
Line 1,620:
=={{header|Nim}}==
<
proc commonprefix(paths: openarray[string], sep = "/"): string =
Line 1,632:
result = result[0 .. result.rfind(sep)]
echo commonprefix(@["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"])</
Output:
<pre>/home/user1/tmp</pre>
Line 1,638:
=={{header|OCaml}}==
<
if List.mem [] paths
then (List.rev acc) else
Line 1,664:
] in
print_endline (common_prefix "/" dirs);
;;</
(uses the module <code>[http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html Str]</code>, str.cma)
=={{header|OpenEdge/Progress}}==
<
i_cdirs AS CHAR,
i_cseparator AS CHAR
Line 1,699:
RETURN cresult.
END FUNCTION.</
<
findCommonDir(
'/home/user1/tmp/coverage/test' + '~n' +
Line 1,708:
'/'
)
VIEW-AS ALERT-BOX</
Output
Line 1,722:
=={{header|Oz}}==
With a few helper functions, we can express the solution like this in Oz:
<
fun {CommonPrefix Sep Paths}
fun {GetParts P} {String.tokens P Sep} end
Line 1,753:
["/home/user1/tmp/coverage/test"
"/home/user1/tmp/covert/operator"
"/home/user1/tmp/coven/members"]}}</
=={{header|PARI/GP}}==
<
my(s="");
v=apply(t->Vec(t),v);
Line 1,767:
if(vecmax(apply(length,v))==vecmin(apply(length,v)),concat(v[1]),s)
};
cdp(["/home/user1/tmp/coverage/test","/home/user1/tmp/covert/operator","/home/user1/tmp/coven/members"])</
=={{header|Perl}}==
Line 1,773:
A solution which lets the regex engine do all the work ''(it operates on the concatenation of the given paths delimited by null-bytes, which should be safe since null-bytes are not allowed inside paths)'':
<
my $sep = shift;
my $paths = join "\0", map { $_.$sep } @_;
$paths =~ /^ ( [^\0]* ) $sep [^\0]* (?: \0 \1 $sep [^\0]* )* $/x;
return $1;
}</
A more conventional solution, which tallies up all potential prefixes from the given paths and then looks for the longest one that occurred the same number of times as there are paths:
<
sub common_prefix {
Line 1,793:
return first { $prefixes{$_} == @paths } reverse sort keys %prefixes;
}</
'''Testing:'''
<
/home/user1/tmp/covert/operator
/home/user1/tmp/coven/members);
print common_prefix('/', @paths), "\n";</
{{out}}
Line 1,809:
To change that behaviour, simply remove both the [1..-2]<br>
For cross-platform operation, simply use the split_path and join_path builtins (not pwa/p2js compatible) instead of split and join.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">common_directory_path</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">paths</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">sep</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'/'</span><span style="color: #0000FF;">)</span>
Line 1,833:
<span style="color: #008000;">"/home/user1/tmp/coven/members"</span><span style="color: #0000FF;">}</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">common_directory_path</span><span style="color: #0000FF;">(</span><span style="color: #000000;">test</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 1,840:
=={{header|PHP}}==
<
/*
Line 1,896:
}
?></
<
/* A more compact string-only version, which I assume would be much faster */
Line 1,920:
}
?></
=={{header|Picat}}==
Line 1,927:
===Using maxof/2===
Using <code>maxof/2</code> to get the longest common prefix.
<
maxof( (common_prefix(Dirs, Path,Len), append(_,"/",Path)), Len).
Line 1,938:
append(Prefix,_,L)
end,
Len = Prefix.length.</
===Mode-directed tabling===
Using mode-directed tabling for maximizing the length.
<
common_prefix2(Dirs,Path,'/',_Len).
Line 1,957:
Prefix.last() == Last
end,
Len = Prefix.length.</
For the directories
Line 1,972:
=={{header|PicoLisp}}==
<
(glue Chr
(make
(apply find
(mapcar '((L) (split (chop L) Chr)) Lst)
'(@ (or (pass <>) (nil (link (next))))) ) ) ) )</
Output:
<pre>(commonPath
Line 1,989:
=={{header|Pike}}==
<
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members" });
Line 1,999:
string cp = String.common_prefix(paths);
cp = cp[..sizeof(cp)-search(reverse(cp), "/")-2];
Result: "/home/user1/tmp"</
=={{header|PowerBASIC}}==
{{Trans|Visual Basic}}
<
#DIM ALL
#COMPILER PBCC 6
Line 2,070:
CON.WAITKEY$
END FUNCTION</
{{out}}
<pre>/home/user1/tmp/coverage/test
Line 2,090:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<#
.Synopsis
Line 2,118:
}
}
</syntaxhighlight>
Sample execution:
<syntaxhighlight lang="text">
"C:\a\b\c\d\e","C:\a\b\e\f","C:\a\b\c\d\x" | Get-CommonPath
C:\a\b
</syntaxhighlight>
=={{header|Prolog}}==
<
%! directory_prefix(PATHs,STOP0,PREFIX)
Line 2,179:
.
</syntaxhighlight>
{{out}}
Line 2,192:
Simply by checking the catalog names until they mismatch and add up the correct parts, the task is accomplished.
<
Protected SOut$=""
Protected i, j, toggle
Line 2,214:
Next
ForEver
EndProcedure</
Example of implementation
<
t(0)="/home/user1/tmp/coverage/test"
t(1)="/home/user1/tmp/covert/operator"
t(2)="/home/user1/tmp/coven/members"
Debug CommonPath(t(),"/"))</
=={{header|Python}}==
Since Python 3.5 os.path.commonpath function can be used:
<
>>> os.path.commonpath(['/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'</
The Python os.path.commonprefix function is [http://nedbatchelder.com/blog/201003/whats_the_point_of_ospathcommonprefix.html broken] as it returns common characters that may not form a valid directory path:
<
>>> os.path.commonprefix(['/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp/cove'</
This result can be fixed:
<
return os.path.commonprefix(args).rpartition(sep)[0]
>>> commonprefix(['/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'</
Even shorter:
<
>>> os.path.dirname(os.path.commonprefix(paths))
'/home/user1/tmp'</
But it may be better to not rely on the faulty implementation at all:
<
>>> def allnamesequal(name):
return all(n==name[0] for n in name[1:])
Line 2,267:
'/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'
>>> </
=={{header|R}}==
<syntaxhighlight lang="r">
get_common_dir <- function(paths, delim = "/")
{
Line 2,293:
get_common_dir(paths) # "/home/user1/tmp"
</syntaxhighlight>
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 2,315:
"/home/user1/tmp/coven/members")
;; --> "/home/user1/tmp"
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
my @dirs = </home/user1/tmp/coverage/test
/home/user1/tmp/covert/operator
Line 2,334:
say "The longest common path is $prefix";
</syntaxhighlight>
Output:
<pre>
Line 2,340:
</pre>
If you'd prefer a pure FP solution without side effects, you can use this:
<syntaxhighlight lang="raku"
my @dirs := </home/user1/tmp/coverage/test
/home/user1/tmp/covert/operator
Line 2,351:
last unless all(@comps[*]»[$column]) eq @comps[0][$column];
take @comps[0][$column] // last;
}</
Or here's another factoring, that focuses on building the result with cumulative sequences and getting the solution with `first`:
<syntaxhighlight lang="raku"
my @dirs = </home/user1/tmp/coverage/test
/home/user1/tmp/covert/operator
Line 2,360:
sub is_common_prefix { so $^prefix eq all(@dirs).substr(0, $prefix.chars) }
say ([\~] @dirs.comb(/ $sep [ <!before $sep> . ]* /)).reverse.first: &is_common_prefix</
=={{header|REXX}}==
<
@. = /*the default for all file lists (null)*/
@.1 = '/home/user1/tmp/coverage/test'
Line 2,381:
if common=='' then common= "/" /*if no common directory, assume home. */
say 'common directory path: ' common /* [↑] handle trailing / delimiter*/
/*stick a fork in it, we're all done. */</
{{out|output|text= when using the default inputs:}}
<pre>
Line 2,388:
=={{header|Ring}}==
<
# Project : Find common directory path
Line 2,413:
end
return left(p[1], o-1)
</syntaxhighlight>
Output:
<pre>
Line 2,422:
Uses the standard library <code>[http://www.ruby-doc.org/stdlib/libdoc/abbrev/rdoc/index.html abbrev]</code> module: Given a set of strings, calculate the set of unambiguous abbreviations for those strings, and return a hash where the keys are all the possible abbreviations and the values are the full strings.
<
dirs = %w( /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members )
common_prefix = dirs.abbrev.keys.min_by {|key| key.length}.chop # => "/home/user1/tmp/cove"
common_directory = common_prefix.sub(%r{/[^/]*$}, '') # => "/home/user1/tmp"</
Implementing without that module:
<
path0, *paths = dirs.collect {|dir| dir.split(separator)}
uncommon_idx = path0.zip(*paths).index {|dirnames| dirnames.uniq.length > 1}
uncommon_idx = path0.length unless uncommon_idx # if uncommon_idx==nil
common_directory = path0[0...uncommon_idx].join(separator) # => "/home/user1/tmp"</
or method version
<
dir1, dir2 = dirs.minmax.map{|dir| dir.split(separator)}
dir1.zip(dir2).take_while{|dn1,dn2| dn1==dn2}.map(&:first).join(separator)
end
p common_directory_path(dirs) #=> "/home/user1/tmp"</
=={{header|Run BASIC}}==
<
' Find common directory to all directories
' and directories common with other Paths
Line 2,530:
html "</TABLE>"
wait
end</
========= Common paths ================<br />
shows only the first few common paths..
Line 2,571:
Rust has specific types for owned and borrowed paths. PathBuf is an 'owned' pointer to a path, Path is a borrow; this is similar to String and str, respectively.
<syntaxhighlight lang="rust">
use std::path::{Path, PathBuf};
Line 2,622:
}
}
</syntaxhighlight>
=={{header|Scala}}==
===Naive===
This simple solution solves the task as given, but has oddities for edge cases due to the implementation of java.lang.String#split.
<
def commonPath(paths: List[String]): String = {
def common(a: List[String], b: List[String]): List[String] = (a, b) match {
Line 2,643:
)
println(commonPath(test))
}</
Output:
<pre>/home/user1/tmp</pre>
===Advanced===
This implementation will handle various edge cases and relative paths. It also includes any common trailing '/' but callers can remove this if desired.
<
def commonPath(paths: List[String]): String = {
val SEP = "/"
Line 2,697:
assert(commonPath(List("/a/a/", "/a/b/")) == "/a/")
assert(commonPath(List("/a/b/", "/a/b/")) == "/a/b/")
}</
=={{header|Seed7}}==
Line 2,707:
but they need to make sure that a path does not end with a slash.
<
const func integer: commonLen (in array string: names, in char: sep) is func
Line 2,748:
writeln("Common path: " <& names[1][.. length]);
end if;
end func;</
Output:
Line 2,756:
=={{header|Sidef}}==
<
/home/user1/tmp/coverage/test
/home/user1/tmp/covert/operator
Line 2,764:
var unique_pref = dirs.map{.split('/')}.abbrev.min_by{.len};
var common_dir = [unique_pref, unique_pref.pop][0].join('/');
say common_dir; # => /home/user1/tmp</
=={{header|Standard ML}}==
<
| takeWhileEq (_, []) = []
| takeWhileEq (x :: xs, y :: ys) =
Line 2,787:
]
val () = print (commonPath #"/" paths ^ "\n")</
=={{header|Swift}}==
Line 2,793:
The below solution works only in swift in Linux.
<
Line 2,809:
var output:String = getPrefix(test)!
print(output)</
=={{header|Tcl}}==
<
proc pop {varname} {
upvar 1 $varname var
Line 2,830:
}
return [join $parts $separator]
}</
<pre>% common_prefix {/home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members}
Line 2,836:
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
common=""
Line 2,851:
ENDIF
ENDLOOP
</syntaxhighlight>
Output:
<pre>
Line 2,859:
=={{header|UNIX Shell}}==
The following is a pure Bourne Shell solution. The while loop controls the maximum depth to check paths.
<
#!/bin/sh
Line 2,880:
i=`expr $i + 1`
done
</syntaxhighlight>
=={{header|Ursala}}==
The algorithm is to lex the paths into component directory names, and then find the greatest common prefix of those.
<
comdir"s" "p" = mat"s" reduce(gcp,0) (map sep "s") "p"</
where <code>"s"</code> is a dummy variable representing the separator, <code>"p"</code> is a dummy variable representing the list of paths, and
*<code>sep</code> is second order function in the standard library that takes a separator character and returns a lexer mapping a string containing the separator to a list of the substrings found between occurrences of it
Line 2,894:
*<code>mat</code> is a second order function in the standard library that takes a separator character and returns a function that flattens a list of strings into a single string with copies of the separator inserted between them
Here is a version using operators instead of mnemonics for <code>map</code> and <code>reduce</code>.
<
Here is one in partly point-free form, using the composition operator (<code>+</code>).
<
Here it is in point-free form.
<
test program:
<
test =
Line 2,907:
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members'></
output:
<pre>'/home/user1/tmp'</pre>
Line 2,915:
=={{header|VBScript}}==
{{works with|Windows Script Host|*}}
<syntaxhighlight lang="vbscript">
' Read the list of paths (newline-separated) into an array...
strPaths = Split(WScript.StdIn.ReadAll, vbCrLf)
Line 2,947:
' Remove the final "/"...
WScript.Echo Left(strPath, Len(strPath) - 1)
</syntaxhighlight>
=={{header|Visual Basic}}==
Line 2,954:
{{works with|VBA|6.5}}
{{works with|VBA|7.1}}
<
Dim v As Variant
Dim Path() As String, s As String
Line 3,013:
"/"
End Sub</
=={{header|Wren}}==
<
var count = paths.count
if (count == 0) return ""
Line 3,045:
]
System.write("The common directory path is: ")
System.print(findCommonDir.call(paths, "/"))</
{{out}}
Line 3,054:
=={{header|Yabasic}}==
{{trans|GW-BASIC}}
<
y$ = "/home/user1/tmp/covert/operator"
z$ = "/home/user1/tmp/coven/members"
Line 3,079:
REM Task description says no trailing slash, so...
a = i - 1
print "Common path is '", left$(x$, a), "'"</
=={{header|zkl}}==
<
"/home/user1/tmp/coven/members");
n:=Utils.zipWith('==,dirs.xplode()).find(False); // character pos which differs
n=dirs[0][0,n].rfind("/"); // find last "/"
dirs[0][0,n];</
{{out}}
<pre>
|