aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xchallenge-236/perlboy1967/perl/ch1.pl58
-rwxr-xr-xchallenge-236/perlboy1967/perl/ch2.pl51
2 files changed, 109 insertions, 0 deletions
diff --git a/challenge-236/perlboy1967/perl/ch1.pl b/challenge-236/perlboy1967/perl/ch1.pl
new file mode 100755
index 0000000000..c0d8f73b9f
--- /dev/null
+++ b/challenge-236/perlboy1967/perl/ch1.pl
@@ -0,0 +1,58 @@
+#!/bin/perl
+
+=pod
+
+The Weekly Challenge - 236
+- https://theweeklychallenge.org/blog/perl-weekly-challenge-236
+
+Author: Niels 'PerlBoy' van Dijke
+
+Task 1: Exact Change
+Submitted by: Mohammad S Anwar
+
+You are asked to sell juice each costs $5. You are given an array of bills. You can only
+sell ONE juice to each customer but make sure you return exact change back. You only have
+$5, $10 and $20 notes. You do not have any change in hand at first.
+
+Write a script to find out if it is possible to sell to each customers with correct change.
+
+=cut
+
+use v5.16;
+
+use common::sense;
+
+use Test::More;
+
+sub exactChange (@) {
+ my %r = (5 => 0, 10 => 0, 20 => 0);
+
+ for (@_) {
+ if ($_ == 5) {
+ $r{5}++;
+ } elsif ($_ == 10) {
+ return 0 if ($r{5} < 1);
+ $r{5}--; $r{10}++;
+ } elsif ($_ == 20) {
+ my $v = $_;
+ if ($r{10} > 0) {
+ $r{10}--; $v -= 10;
+ }
+ my $n = ($v - 5) / 5;
+ return 0 if ($r{5} < $n);
+ $r{5} -= $n; $r{20}++;
+ } else {
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+is(exactChange(5,5,5,10,20),1);
+is(exactChange(5,5,10,10,20),0);
+is(exactChange(5,5,5,20),1);
+is(exactChange(5,5,20),0);
+is(exactChange(5,10,5,10,20),0);
+
+done_testing;
diff --git a/challenge-236/perlboy1967/perl/ch2.pl b/challenge-236/perlboy1967/perl/ch2.pl
new file mode 100755
index 0000000000..0df3f42d16
--- /dev/null
+++ b/challenge-236/perlboy1967/perl/ch2.pl
@@ -0,0 +1,51 @@
+#!/bin/perl
+
+=pod
+
+The Weekly Challenge - 236
+- https://theweeklychallenge.org/blog/perl-weekly-challenge-236
+
+Author: Niels 'PerlBoy' van Dijke
+
+Task 2: Array Loops
+Submitted by: Mark Anderson
+
+You are given an array of unique integers.
+
+Write a script to determine how many loops are in the given array.
+
+|| To determine a loop: Start at an index and take the number at array[index]
+|| and then proceed to that index and continue this until you end up at the starting index.
+
+=cut
+
+use v5.16;
+
+use common::sense;
+
+use Test::More;
+
+sub arrayLoops (@) {
+ my ($n,%u) = (0);
+
+ for my $i (0 .. scalar(@_)-1) {
+ next if exists $u{$i};
+
+ my $j = $_[$i];
+ while (!exists $u{$j}) {
+ last if ($j < 0 or $j >= scalar(@_));
+ $j = $u{$j} = $_[$j];
+ }
+
+ $n++ if (exists $u{$j});
+ }
+ return $n;
+}
+
+is(arrayLoops(4,6,3,8,15,0,13,18,7,16,14,19,17,5,11,1,12,2,9,10),3);
+is(arrayLoops(0,1,13,7,6,8,10,11,2,14,16,4,12,9,17,5,3,18,15,19),6);
+is(arrayLoops(0,3,1,2),2);
+is(arrayLoops(0,1,5,2),2);
+is(arrayLoops(-1),0);
+
+done_testing;