aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordasJake <no_mail@github.com>2021-11-27 17:31:05 +0100
committerdasJake <no_mail@github.com>2021-11-27 17:31:05 +0100
commitb8230b5d16e0d0e44c47dee28a9e00a33f1b8d25 (patch)
treef399479509b543f8a03d1f1f83dca3ebf40586fc
parent05436a73750a6f51db4bcae860c1991e83179191 (diff)
downloadperlweeklychallenge-club-b8230b5d16e0d0e44c47dee28a9e00a33f1b8d25.tar.gz
perlweeklychallenge-club-b8230b5d16e0d0e44c47dee28a9e00a33f1b8d25.tar.bz2
perlweeklychallenge-club-b8230b5d16e0d0e44c47dee28a9e00a33f1b8d25.zip
140 add ch-2.pl
-rw-r--r--challenge-140/jake/perl/ch-2.pl57
1 files changed, 57 insertions, 0 deletions
diff --git a/challenge-140/jake/perl/ch-2.pl b/challenge-140/jake/perl/ch-2.pl
new file mode 100644
index 0000000000..830111b0c6
--- /dev/null
+++ b/challenge-140/jake/perl/ch-2.pl
@@ -0,0 +1,57 @@
+#!/r/bin/perl
+
+use strict;
+use warnings;
+use feature 'say';
+
+###
+# You are given 3 positive integers, $i, $j and $k.
+#
+# Write a script to print the $kth element in the sorted multiplication table of $i and $j.
+#
+# https://theweeklychallenge.org/blog/perl-weekly-challenge-140/#TASK2
+###
+
+# get input
+print "height: ";
+my $height = <STDIN>;
+print "width: ";
+my $width = <STDIN>;
+print "element to display: ";
+my $element = <STDIN>;
+chomp ( $height, $width, $element );
+
+# sort multiplication table
+my @sorted = sort { $a <=> $b } @{aggregate_multiplication_table ( $height, $width )};
+
+# output desired element
+say ( $sorted[$element - 1] );
+
+# container sub so main needs to pass only 2 arguments
+sub aggregate_multiplication_table {
+ my ( $height, $width ) = @_;
+ _aggregate_multiplication_table ( $height, $width, 1 );
+}
+
+sub _aggregate_multiplication_table {
+ my ( $vertical_range, $horizontal_range, $height_increment, $horizontal_values, $all_values ) = @_;
+
+ # access lists from references
+ my @horizontal_values = @{$horizontal_values // []};
+ my @all_values = @{$all_values // []};
+
+ # once all lines of the table have been written we can return @all_values
+ return \@all_values if $height_increment > $vertical_range;
+
+ # we 'write' the first line of the multiplication table.
+ # after that we run over each value in this first adding each new value to the accumulator @all_values.
+ # we will repeat this for every line that needs to be added to the table.
+ @horizontal_values = 1 ... $horizontal_range;
+ foreach ( @horizontal_values ) {
+ push @all_values, $_ * $height_increment;
+ }
+
+ # we need to increase our line counter upon iteration.
+ # this is necessary for our foreach loop to add the next line in the following iteration.
+ return _aggregate_multiplication_table ( $vertical_range, $horizontal_range, $height_increment + 1, \@horizontal_values, \@all_values );
+} \ No newline at end of file