From 271548a652fafedd5e43009f437c7e086209ba9d Mon Sep 17 00:00:00 2001 From: Torgny Lyon Date: Mon, 26 Aug 2024 13:06:59 +0200 Subject: Add solutions for week 284 --- challenge-284/torgny-lyon/README | 1 + challenge-284/torgny-lyon/perl/ch-1.pl | 18 ++++++++++++++++++ challenge-284/torgny-lyon/perl/ch-2.pl | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+) create mode 100644 challenge-284/torgny-lyon/README create mode 100755 challenge-284/torgny-lyon/perl/ch-1.pl create mode 100755 challenge-284/torgny-lyon/perl/ch-2.pl diff --git a/challenge-284/torgny-lyon/README b/challenge-284/torgny-lyon/README new file mode 100644 index 0000000000..2ad0e668a3 --- /dev/null +++ b/challenge-284/torgny-lyon/README @@ -0,0 +1 @@ +Solution by Torgny Lyon. diff --git a/challenge-284/torgny-lyon/perl/ch-1.pl b/challenge-284/torgny-lyon/perl/ch-1.pl new file mode 100755 index 0000000000..f68acee6bc --- /dev/null +++ b/challenge-284/torgny-lyon/perl/ch-1.pl @@ -0,0 +1,18 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +use List::Util qw(uniq); +use Test::More tests => 3; + +sub get_lucky { + foreach my $n (uniq sort { $b <=> $a } @_) { + return $n if (grep { $_ == $n } @_) == $n; + } + return -1; +} + +is(get_lucky(2, 2, 3, 4), 2); +is(get_lucky(1, 2, 2, 3, 3, 3), 3); +is(get_lucky(1, 1, 1, 3), -1); diff --git a/challenge-284/torgny-lyon/perl/ch-2.pl b/challenge-284/torgny-lyon/perl/ch-2.pl new file mode 100755 index 0000000000..b1a3bec1e6 --- /dev/null +++ b/challenge-284/torgny-lyon/perl/ch-2.pl @@ -0,0 +1,32 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +use Test::More tests => 3; + +sub sort_relative { + my @list1 = @{ $_[0] }; + my @list2 = @{ $_[1] }; + my @r; + foreach my $x (@list2) { + push @r, grep { $x == $_ } @list1; + } + return @r, sort grep { my $x = $_; !grep { $x == $_ } @list2 } @list1; +} + +is_deeply( + [ + sort_relative( + [ 2, 3, 9, 3, 1, 4, 6, 7, 2, 8, 5 ], + [ 2, 1, 4, 3, 5, 6 ] + ) + ], + [ 2, 2, 1, 4, 3, 3, 5, 6, 7, 8, 9 ] +); + +is_deeply([ sort_relative([ 3, 3, 4, 6, 2, 4, 2, 1, 3 ], [ 1, 3, 2 ]) ], + [ 1, 3, 3, 3, 2, 2, 4, 4, 6 ]); + +is_deeply([ sort_relative([ 3, 0, 5, 0, 2, 1, 4, 1, 1 ], [ 1, 0, 3, 2 ]) ], + [ 1, 1, 1, 0, 0, 3, 2, 4, 5 ]); -- cgit