From b8d4ba46cfd21a36c9939ea950666141888a258b Mon Sep 17 00:00:00 2001 From: 冯昶 Date: Sun, 16 Jun 2019 00:53:13 +0800 Subject: challenge 012 #2 --- challenge-012/feng-chang/perl5/ch-2.pl | 27 +++++++++++++++++++++++++++ challenge-012/feng-chang/perl5/paths.txt | 4 ++++ challenge-012/feng-chang/perl6/ch-2.p6 | 17 +++++++++++++++++ challenge-012/feng-chang/perl6/paths.txt | 4 ++++ 4 files changed, 52 insertions(+) create mode 100755 challenge-012/feng-chang/perl5/ch-2.pl create mode 100644 challenge-012/feng-chang/perl5/paths.txt create mode 100755 challenge-012/feng-chang/perl6/ch-2.p6 create mode 100644 challenge-012/feng-chang/perl6/paths.txt diff --git a/challenge-012/feng-chang/perl5/ch-2.pl b/challenge-012/feng-chang/perl5/ch-2.pl new file mode 100755 index 0000000000..c3c26e5f79 --- /dev/null +++ b/challenge-012/feng-chang/perl5/ch-2.pl @@ -0,0 +1,27 @@ +#!/bin/env perl + +use Modern::Perl; +use List::Util qw(reduce); + +sub common_prefix { + my ($a, $b) = @_; + my @a = split //, $a; + my @b = split //, $b; + + my $r = ''; + my $i = 0; + while ($a[$i] && $b[$i] && $a[$i] eq $b[$i]) { + $r .= $a[$i++]; + } + + return $r; +} + +chomp(my @paths = <>); +my $common_path = reduce { common_prefix($a, $b) } @paths; + +my @c = split //, $common_path; +pop @c while $c[-1] ne '/'; +pop @c if @c > 1; + +say 'common directory path: ', join('', @c); diff --git a/challenge-012/feng-chang/perl5/paths.txt b/challenge-012/feng-chang/perl5/paths.txt new file mode 100644 index 0000000000..1427e2dbc8 --- /dev/null +++ b/challenge-012/feng-chang/perl5/paths.txt @@ -0,0 +1,4 @@ +/a/b/c/d +/a/b/cd +/a/b/cc +/a/b/c/d/e diff --git a/challenge-012/feng-chang/perl6/ch-2.p6 b/challenge-012/feng-chang/perl6/ch-2.p6 new file mode 100755 index 0000000000..1ea095468d --- /dev/null +++ b/challenge-012/feng-chang/perl6/ch-2.p6 @@ -0,0 +1,17 @@ +#!/bin/env perl6 + +sub common_prefix(Str $a, Str $b) { + my @a = $a.comb; + my @b = $b.comb; + + for 0..∞ -> $i { + last unless @a[$i].defined && @b[$i].defined && @a[$i] eq @b[$i]; + LAST { return @a[0 .. $i - 1].join } + } +} + +my @c = ([[&common_prefix]] 'paths.txt'.IO.lines).comb; +@c.pop while @c[* - 1] ne '/'; +@c.pop if @c.elems > 1; + +say 'common directory path: ', @c.join; diff --git a/challenge-012/feng-chang/perl6/paths.txt b/challenge-012/feng-chang/perl6/paths.txt new file mode 100644 index 0000000000..1427e2dbc8 --- /dev/null +++ b/challenge-012/feng-chang/perl6/paths.txt @@ -0,0 +1,4 @@ +/a/b/c/d +/a/b/cd +/a/b/cc +/a/b/c/d/e -- cgit