aboutsummaryrefslogtreecommitdiff
path: root/challenge-012/arne-sommer/perl6/common-dir-path2
blob: 81e6f83d69b3c6d12c4dbe417135af36d51b36dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#! /usr/bin/env perl6

unit sub MAIN (:$separator = "/", *@paths is copy);

loop
{
  my $size = @paths>>.chars.sum;
  
  @paths = remove-last-part(@paths);

  unless @paths.elems
  {
    say "No common Directory Path.";
    last;
  }

  if all(@paths) eq @paths[0]
  {
    @paths[0] eq $separator
      ?? say "Common Directory Path: $separator"
      !! say "Common Directory Path: " ~ @paths[0].substr(0, @paths[0].chars - $separator.chars);
    last;
  }
  
  if (@paths>>.chars.sum == $size) { @paths[0] = @paths[0].substr(0, @paths[0].chars - $separator.chars); }
}

sub remove-last-part(@paths)
{
  my @new;
  for @paths
  {
    return () unless /$separator/;
    /(.*$separator)/;
    push @new: $0.Str;
  }
  
  my $min = @new>>.chars.min;

  my @return; for @new { @return.push($_.substr(0, $min)); }
  return @return;
}