aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--challenge-080/ted-leahy/perl/ch-1.pl36
-rw-r--r--challenge-080/ted-leahy/perl/ch-2.pl37
2 files changed, 73 insertions, 0 deletions
diff --git a/challenge-080/ted-leahy/perl/ch-1.pl b/challenge-080/ted-leahy/perl/ch-1.pl
new file mode 100644
index 0000000000..6e18bd910f
--- /dev/null
+++ b/challenge-080/ted-leahy/perl/ch-1.pl
@@ -0,0 +1,36 @@
+# # Smallest Positive Integer # #
+# - You are given unsorted list of integers @N.
+# - Write a script to find out the smallest positive number missing.
+# #
+
+use strict;
+use warnings;
+use feature 'say';
+
+my @N = @ARGV || (5, 2, -2, 0);
+
+# Filter out negative numbers and sort the resulting array
+@N = sort (grep { $_ >= 0 } @N);
+
+# if there are only negative numbers in the array, return 1, as that's the smallest possible positive number.
+if (!@N) {
+ say 1;
+ exit;
+}
+
+for my $i (0..$#N) {
+ my $current_n = $N[$i];
+ my $next_n = $N[$i+1] || 0;
+ my $distance_between_ns = abs($current_n - $next_n);
+
+ if ($distance_between_ns > 1) {
+ say $current_n + 1;
+ exit;
+ }
+}
+
+# If there's no missing element, then return the last element of the array + 1; you could maybe say that's
+# technically the smallest positive number missing, as it's missing from the end of the array.
+say $N[-1] + 1;
+
+1; \ No newline at end of file
diff --git a/challenge-080/ted-leahy/perl/ch-2.pl b/challenge-080/ted-leahy/perl/ch-2.pl
new file mode 100644
index 0000000000..06c0b845fc
--- /dev/null
+++ b/challenge-080/ted-leahy/perl/ch-2.pl
@@ -0,0 +1,37 @@
+# # Count Candies # #
+# - You are given rankings of @N candidates.
+# - Write a script to find out the total candies needed for all candidates.
+# You are asked to follow the rules below:
+# a) You must given at least one candy to each candidate.
+# b) Candidates with higher rankings get more candies than their immediate neighbors on either side.
+# #
+
+use strict;
+use warnings;
+use feature 'say';
+
+my @N = @ARGV || (1, 2, 2);
+
+my $total_candies = 0;
+
+# Applying rule #a, each candidate must get at least one candy
+$total_candies += scalar @N;
+
+# Applying rule #b, each candidate that has a higher ranking than its neighbour(s)
+# gets an additional piece of candy for each lower-ranking neighbour
+for my $i (0..$#N) {
+ my $current_candidate_rank = $N[$i];
+ my $next_candidate_rank = $N[$i+1];
+ my $previous_candidate_rank = $N[$i-1];
+
+ if ($next_candidate_rank && $current_candidate_rank > $next_candidate_rank) {
+ $total_candies++;
+ }
+ if ($previous_candidate_rank && $current_candidate_rank > $previous_candidate_rank) {
+ $total_candies++;
+ }
+}
+
+say $total_candies;
+
+1; \ No newline at end of file