diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2020-07-06 23:08:54 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-07-06 23:08:54 +0100 |
| commit | f86a1d9a0561844fac885a0ab052f765a9df8032 (patch) | |
| tree | 817890760e5371eb15404bf23755780e58b003cc | |
| parent | 0486402dfb99dc3b6d940989cbe83b3ae0153b8b (diff) | |
| parent | a8a0788c78e27af2402a2cc776561c2724eebb36 (diff) | |
| download | perlweeklychallenge-club-f86a1d9a0561844fac885a0ab052f765a9df8032.tar.gz perlweeklychallenge-club-f86a1d9a0561844fac885a0ab052f765a9df8032.tar.bz2 perlweeklychallenge-club-f86a1d9a0561844fac885a0ab052f765a9df8032.zip | |
Merge pull request #1916 from choroba/ech068
Solve 068: Zero Matrix & Reorder List by E. Choroba
| -rwxr-xr-x | challenge-068/e-choroba/perl5/ch-1.pl | 19 | ||||
| -rwxr-xr-x | challenge-068/e-choroba/perl5/ch-2.pl | 61 |
2 files changed, 80 insertions, 0 deletions
diff --git a/challenge-068/e-choroba/perl5/ch-1.pl b/challenge-068/e-choroba/perl5/ch-1.pl new file mode 100755 index 0000000000..da15d2f5ef --- /dev/null +++ b/challenge-068/e-choroba/perl5/ch-1.pl @@ -0,0 +1,19 @@ +#!/usr/bin/perl +use warnings; +use strict; + +use PDL; + +sub zero_matrix { + my ($matrix) = @_; + my $pdl = pdl($matrix); + return unpdl(andover($pdl->xchg(0,1)) * transpose(andover($pdl))) +} + +use Test::More tests => 2; + +is_deeply zero_matrix([[1, 0, 1], [1, 1, 1], [1, 1, 1]]), + [[0, 0, 0],[1, 0, 1],[1, 0, 1]]; + +is_deeply zero_matrix([[1, 0, 1], [1, 1, 1], [1, 0, 1]]), + [[0, 0, 0], [1, 0, 1], [0, 0, 0]]; diff --git a/challenge-068/e-choroba/perl5/ch-2.pl b/challenge-068/e-choroba/perl5/ch-2.pl new file mode 100755 index 0000000000..7e81ecbccc --- /dev/null +++ b/challenge-068/e-choroba/perl5/ch-2.pl @@ -0,0 +1,61 @@ +#!/usr/bin/perl +use warnings; +use strict; +use feature qw{ say }; + +{ package My::Node; + sub new { bless { value => $_[1] }, $_[0] } + sub set_next { $_[0]->{next} = $_[1] } + + sub serialize { + my ($self) = @_; + my $n = $self; + my @s; + while (defined $n) { + push @s, $n->{value}; + $n = $n->{next} + } + @s + } + + sub new_from_list { + my ($class, @values) = @_; + my $self = bless { value => shift @values }, $class; + my $last = $self; + for (@values) { + my $next = $class->new($_); + $last->set_next($next); + $last = $next; + } + return $self + } + + sub reorder { + my ($self) = @_; + my $current = $self; + while ($current) { + my $last = $current; + my $last_but_one; + while ($last->{next}) { + $last_but_one = $last; + $last = $last->{next}; + } + + undef $last_but_one->{next}; + my $next = $current->{next}; + $current->set_next($last); + $last->set_next($next); + $current = $next; + } + } +} + +use Test::More tests => 2; + +my $list = 'My::Node'->new_from_list(1 .. 4); +$list->reorder; +is_deeply [$list->serialize], [1, 4, 2, 3]; + +my $list2 = 'My::Node'->new_from_list(1 .. 5); +$list2->reorder; +is_deeply [$list2->serialize], [1, 5, 2, 4, 3]; |
