Find common directory path: Difference between revisions
→{{header|K}}
imported>Regattaguru |
|||
(4 intermediate revisions by 2 users not shown) | |||
Line 1,441:
for their common directory path yields:
/home/user1/tmp</pre>
=={{header|K}}==
<syntaxhighlight lang="k">
fcp:{"/"/(+/*\1=#'?'+y\'x)#("/"\ x@0)}
/example usage
l:("/home/user1/tmp/coverage/test"; "/home/user1/tmp/covert/operator"; "/home/user1/tmp/coven/members")
fcp[l;"/"]
"/home/user1/tmp"
</syntaxhighlight>
=={{header|Kotlin}}==
Line 1,850 ⟶ 1,861:
};
cdp(["/home/user1/tmp/coverage/test","/home/user1/tmp/covert/operator","/home/user1/tmp/coven/members"])</syntaxhighlight>
=={{header|Pascal}}==
==={{header|Free Pascal}}===
<syntaxhighlight lang="pascal">
Program CommonPaths;
{$mode ObjFPC}{$H+}
uses
Classes, Math;
const
Paths: array of string = ('/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members');
function FindShortestCommonPath(arr: array of TStringList; shortestPath: Integer): string;
var
i, j: Integer;
commonStr: string;
begin
Result := '/';
if Length(arr) = 0 then
Exit;
for j := 0 to shortestPath - 1 do
begin
commonStr := arr[0][j];
for i := 1 to High(arr) do
begin
if arr[i][j] <> commonStr then
Exit(Result);
end;
Result := Result + commonStr + '/';
end;
end;
var
arr: array of TStringList;
i, shortestpath: uint32;
begin
shortestpath := High(uint32);
SetLength(arr, Length(paths));
for i := 0 to High(paths) do
begin
arr[i] := TStringList.Create;
arr[i].AddDelimitedText(paths[i], '/', false);
arr[i].Delete(0);
shortestpath := Min(shortestpath, arr[i].Count);
end;
Writeln(FindShortestCommonPath(arr, shortestpath));
for i := 0 to High(paths) do
arr[i].Free;
end.
</syntaxhighlight>
{{out}}
<pre>
/home/user1/tmp/
</pre>
=={{header|Perl}}==
Line 2,969 ⟶ 3,042:
print(output)</syntaxhighlight>
===Works on MacOS===
<syntaxhighlight lang="swift">
import Foundation
func
for tryLen in (0...min(lhs.count,rhs.count)).reversed() {
if lhs.starts(with: rhs.prefix(tryLen)) {
return Array<T>(rhs.prefix(tryLen))
}
}
return []
}
var test = ["/home/user1/tmp/coverage/test",
let lcp: String = test.reduce("") { lhs, rhs in
if !lhs.isEmpty {
var commonSoFar = commonPrefix(
lhs.components(separatedBy: "/"),
rhs.components(separatedBy: "/")
)
return commonSoFar.joined(separator: "/")
}
return rhs
}
print("Longest common path: \(lcp)")
// Longest common path: /home/user1/tmp
</syntaxhighlight>
|