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