aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJörg Sommrey <28217714+jo-37@users.noreply.github.com>2022-12-30 16:16:53 +0100
committerJörg Sommrey <28217714+jo-37@users.noreply.github.com>2022-12-30 16:22:56 +0100
commita8381ba2598d921ee0b1b17cac9fde49b4a613e1 (patch)
tree48d523f7fbf618e9e8d4020fb65e57c8f273e445
parent52f0922230bfc9ef7949656cfae1cc52f234d636 (diff)
downloadperlweeklychallenge-club-a8381ba2598d921ee0b1b17cac9fde49b4a613e1.tar.gz
perlweeklychallenge-club-a8381ba2598d921ee0b1b17cac9fde49b4a613e1.tar.bz2
perlweeklychallenge-club-a8381ba2598d921ee0b1b17cac9fde49b4a613e1.zip
Solution to task 2
-rwxr-xr-xchallenge-197/jo-37/perl/ch-2.pl68
1 files changed, 68 insertions, 0 deletions
diff --git a/challenge-197/jo-37/perl/ch-2.pl b/challenge-197/jo-37/perl/ch-2.pl
new file mode 100755
index 0000000000..413ed8d0b0
--- /dev/null
+++ b/challenge-197/jo-37/perl/ch-2.pl
@@ -0,0 +1,68 @@
+#!/usr/bin/perl -s
+
+use v5.16;
+use Test2::V0;
+use List::MoreUtils qw(zip part);
+
+our ($tests, $examples);
+
+run_tests() if $tests || $examples; # does not return
+
+die <<EOS unless @ARGV;
+usage: $0 [-examples] [-tests] [--] [N...]
+
+-examples
+ run the examples from the challenge
+
+-tests
+ run some tests
+
+N...
+ list of numbers
+
+EOS
+
+
+### Input and Output
+
+say "@{[wiggle_sort(@ARGV)]}";
+
+
+### Implementation
+
+# Sort the list in descending order, split it in two and zip both parts.
+# For an odd sized list, the first part gets one more element. "zip"
+# will then produce a trailing "undef" that will be omitted by the
+# slice.
+# If the list contains too many replicas of the same element then there
+# is no valid wiggle sorted list and the produced result will silently
+# violate the constraints.
+sub wiggle_sort {
+ my $i;
+ (&zip(
+ part {$i++ < $#_ / 2}
+ sort {$b <=> $a} @_
+ ))[0 .. $#_];
+}
+
+
+### Examples and tests
+
+sub run_tests {
+ SKIP: {
+ skip "examples" unless $examples;
+ is [wiggle_sort(qw(1 5 1 1 6 4))], [qw(1 6 1 5 1 4)], 'example 1';
+ is [wiggle_sort(qw(1 3 2 2 3 1))], [qw(2 3 1 3 1 2)], 'example 2';
+ }
+
+ SKIP: {
+ skip "tests" unless $tests;
+ is [wiggle_sort(qw(1 2 3 4 5))], [qw(3 5 2 4 1)], 'odd size';
+ is [(wiggle_sort(qw(1 1 1 1 1 2 3 4)))[6, 7]], [1, 1], '1 violates';
+ is [(wiggle_sort(qw(1 2 3 4 4 4 4)))[0, 1]], [4, 4], '4 violates';
+ is [wiggle_sort(-1, 0, 1)], [0, 1, -1], 'negative';
+ }
+
+ done_testing;
+ exit;
+}