diff options
| author | E. Choroba <choroba@matfyz.cz> | 2021-11-24 00:32:59 +0100 |
|---|---|---|
| committer | E. Choroba <choroba@matfyz.cz> | 2021-11-24 00:32:59 +0100 |
| commit | 26c8d4c0c50810942c4a8b02dc4f086493d9aeaa (patch) | |
| tree | 5782ab7fbf5f6421c189ea49cb7d2b0b6049ef90 | |
| parent | e57e8ba97ca974deeadbd7137390e99a38d8304d (diff) | |
| download | perlweeklychallenge-club-26c8d4c0c50810942c4a8b02dc4f086493d9aeaa.tar.gz perlweeklychallenge-club-26c8d4c0c50810942c4a8b02dc4f086493d9aeaa.tar.bz2 perlweeklychallenge-club-26c8d4c0c50810942c4a8b02dc4f086493d9aeaa.zip | |
Solve 140: Add Binary & Multiplication Table by E. Choroba
| -rwxr-xr-x | challenge-140/e-choroba/perl/ch-1.pl | 47 | ||||
| -rwxr-xr-x | challenge-140/e-choroba/perl/ch-2.pl | 20 |
2 files changed, 67 insertions, 0 deletions
diff --git a/challenge-140/e-choroba/perl/ch-1.pl b/challenge-140/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..214e130155 --- /dev/null +++ b/challenge-140/e-choroba/perl/ch-1.pl @@ -0,0 +1,47 @@ +#!/usr/bin/perl +use warnings; +use strict; + +{ package Binary; + use Tie::Scalar; + use parent -norequire => 'Tie::StdScalar'; + + sub TIESCALAR { + my ($class, $value) = @_; + die 'Too many arguments' if @_ > 2; + die 'Invalid format' if $value =~ /[^01]/; + bless \$value, $class + } + + sub FETCH { $_[0] } + + use overload + '+' => sub { + sprintf '%b', oct("0b${ $_[0] }") + oct("0b${ $_[1] }") + }, + '""' => sub { ${ $_[0] } }, +} + +use Test::More tests => 4; +use Test::Exception; + +{ throws_ok { + tie my $A, 'Binary', 2; + } qr/Invalid format/, + 'Only binary'; +} + +{ tie my $A, 'Binary', 11; + tie my $B, 'Binary', 1; + is $A + $B, 100, "Example 1 ($A + $B)"; +} + +{ tie my $A, 'Binary', 101; + tie my $B, 'Binary', 1; + is $A + $B, 110, "Example 2 ($A + $B)"; +} + +{ tie my $A, 'Binary', 100; + tie my $B, 'Binary', 11; + is $A + $B, 111, "Example 3 ($A + $B)"; +} diff --git a/challenge-140/e-choroba/perl/ch-2.pl b/challenge-140/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..cc95dfa3bb --- /dev/null +++ b/challenge-140/e-choroba/perl/ch-2.pl @@ -0,0 +1,20 @@ +#!/usr/bin/perl +use warnings; +use strict; + +sub multiplication_table { + my ($i, $j, $k) = @_; + my @t; + for my $l (1 .. $i) { + push @t, map $l * $_, 1 .. $j; + } + return (sort { $a <=> $b } @t)[$k - 1] +} + +use Test::More tests => 4; + +is multiplication_table(2, 3, 4), 3, 'Example 1'; +is multiplication_table(3, 3, 6), 4, 'Example 2'; + +is multiplication_table(10, 12, 44), 18, 'Large table'; +is multiplication_table(10, 12, 45), 20, 'Large table'; |
