aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorE. Choroba <choroba@matfyz.cz>2021-03-30 23:07:16 +0200
committerE. Choroba <choroba@matfyz.cz>2021-03-30 23:07:16 +0200
commitdb3b250b9198a0926f729b4d48affc0eec1d587f (patch)
treeadf424e7f479575a8dbe27dbc0cdcc7128e8613d
parentcf7cc2c5fbb60bb58b354e86dfeecf95f5c97eae (diff)
downloadperlweeklychallenge-club-db3b250b9198a0926f729b4d48affc0eec1d587f.tar.gz
perlweeklychallenge-club-db3b250b9198a0926f729b4d48affc0eec1d587f.tar.bz2
perlweeklychallenge-club-db3b250b9198a0926f729b4d48affc0eec1d587f.zip
Add solution to 106: Maximum Gap & Decimal String by E. Choroba
-rwxr-xr-xchallenge-106/e-choroba/perl5/ch-1.pl18
-rwxr-xr-xchallenge-106/e-choroba/perl5/ch-2.pl36
2 files changed, 54 insertions, 0 deletions
diff --git a/challenge-106/e-choroba/perl5/ch-1.pl b/challenge-106/e-choroba/perl5/ch-1.pl
new file mode 100755
index 0000000000..689cbd73fc
--- /dev/null
+++ b/challenge-106/e-choroba/perl5/ch-1.pl
@@ -0,0 +1,18 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+
+sub maximum_gap {
+ my @arr = sort { $a <=> $b } @_;
+ my $max = 0;
+ for my $i (1 .. $#arr) {
+ my $diff = $arr[$i] - $arr[ $i - 1 ];
+ $max = $diff if $diff > $max;
+ }
+ return $max
+}
+
+use Test::More tests => 3;
+is maximum_gap(2, 9, 3, 5), 4, 'Example 1';
+is maximum_gap(1, 3, 8, 2, 0), 5, 'Example 2';
+is maximum_gap(5), 0, 'Example 3';
diff --git a/challenge-106/e-choroba/perl5/ch-2.pl b/challenge-106/e-choroba/perl5/ch-2.pl
new file mode 100755
index 0000000000..49dafa8e52
--- /dev/null
+++ b/challenge-106/e-choroba/perl5/ch-2.pl
@@ -0,0 +1,36 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+
+sub decimal_string {
+ my ($n, $d) = @_;
+ my ($abs_n, $abs_d) = map abs, $n, $d;
+ my $result = join "",
+ ($n < 0 xor $d < 0) ? '-' : "",
+ int($abs_n / $abs_d),
+ '.';
+ my %seen = (my $remainder = $abs_n % $abs_d => 0);
+ my $i = 1;
+ while ($remainder != 0) {
+ $remainder *= 10;
+ $result .= my $r_digit = int($remainder / $abs_d);
+ my $new_remainder = $remainder % $abs_d;
+ if (exists $seen{$new_remainder}) {
+ substr $result,
+ 1 + index($result, '.') + $seen{$new_remainder},
+ 0, '(';
+ return "$result)"
+ }
+ $seen{ $remainder = $new_remainder } = $i++;
+ }
+ return $result =~ s/\.$/.0/r
+}
+
+use Test::More tests => 6;
+is decimal_string(1, 3), '0.(3)', 'Example 1';
+is decimal_string(1, 2), '0.5', 'Example 2';
+is decimal_string(5, 66), '0.0(75)', 'Example 3';
+
+is decimal_string(-22, 7), '-3.(142857)', '-22/7';
+is decimal_string(3, -8), '-0.375', '3/-8';
+is decimal_string(-99, 9), '-11.0', '-99/9';