aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xchallenge-279/andrezgz/perl/ch-1.pl31
-rwxr-xr-xchallenge-279/andrezgz/perl/ch-2.pl50
2 files changed, 81 insertions, 0 deletions
diff --git a/challenge-279/andrezgz/perl/ch-1.pl b/challenge-279/andrezgz/perl/ch-1.pl
new file mode 100755
index 0000000000..4805be2516
--- /dev/null
+++ b/challenge-279/andrezgz/perl/ch-1.pl
@@ -0,0 +1,31 @@
+#!/usr/bin/perl
+
+# https://theweeklychallenge.org/blog/perl-weekly-challenge-279/
+# TASK #1 > Sort Letters
+#
+# You are given two arrays, @letters and @weights.
+#
+# Write a script to sort the given array @letters based on the @weights.
+
+use strict;
+use warnings;
+use Test2::V0 '-no_srand';
+
+my @tests = (
+ [ ['R', 'E', 'P', 'L'], [3, 2, 1, 4], 'PERL' ],
+ [ ['A', 'U', 'R', 'K'], [2, 4, 1, 3], 'RAKU' ],
+ [ ['O', 'H', 'Y', 'N', 'P', 'T'], [5, 4, 2, 6, 1, 3], 'PYTHON' ],
+);
+
+for my $test (@tests) {
+ my ($letters, $weights, $expected) = @$test;
+ is sorted_by_weight($letters, $weights), $expected;
+}
+
+done_testing;
+
+sub sorted_by_weight {
+ my ($letters, $weights) = @_;
+ my @order = sort { $weights->[$a] <=> $weights->[$b] } 0 .. $#{$letters};
+ return $letters->@[@order];
+}
diff --git a/challenge-279/andrezgz/perl/ch-2.pl b/challenge-279/andrezgz/perl/ch-2.pl
new file mode 100755
index 0000000000..901ac1cc32
--- /dev/null
+++ b/challenge-279/andrezgz/perl/ch-2.pl
@@ -0,0 +1,50 @@
+#!/usr/bin/perl
+
+# https://theweeklychallenge.org/blog/perl-weekly-challenge-279/
+# Task #2 > Split String
+#
+# You are given a string, $str.
+#
+# Write a script to split the given string into two containing exactly same number of vowels and return true if you can otherwise false.
+#
+
+use strict;
+use warnings;
+use Test2::V0 '-no_srand';
+
+my @tests = (
+ [ 'perl', 'false' ],
+ [ 'book', 'true' ],
+ [ 'good morning', 'true' ],
+);
+
+for my $test (@tests) {
+ my ($str, $expected) = @$test;
+ my $splits = splits_with_equal_vowels($str);
+ is any_valid_split($splits) ? 'true' : 'false', $expected;
+}
+
+done_testing;
+
+sub any_valid_split {
+ my $splits = shift;
+ return !! scalar @$splits;
+}
+
+sub splits_with_equal_vowels {
+ my $str = shift;
+
+ # count the number of vowels
+ my $vowels = $str =~ tr/aeiouAEIOU//;
+ return [] if $vowels % 2; # odd number of vowels
+
+ my $res = [];
+ my $count_vw = 0;
+ for my $i (0 .. length($str)/2 - 1) {
+ ++$count_vw if substr($str, $i, 1) =~ /[aeiou]/i;
+ next unless $count_vw == $vowels / 2; # not a valid split point
+ push @$res, [ substr($str, 0, $i+1), substr($str, $i + 1)];
+ }
+
+ return $res;
+}