From 7b6dbcf59d867da8a01679113fa6d470095652b5 Mon Sep 17 00:00:00 2001 From: Dave Jacoby Date: Mon, 6 May 2024 16:27:02 -0400 Subject: DAJ 268 --- challenge-268/dave-jacoby/perl/ch-1.pl | 46 ++++++++++++++++++++++++++++++++++ challenge-268/dave-jacoby/perl/ch-2.pl | 38 ++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 challenge-268/dave-jacoby/perl/ch-1.pl create mode 100644 challenge-268/dave-jacoby/perl/ch-2.pl diff --git a/challenge-268/dave-jacoby/perl/ch-1.pl b/challenge-268/dave-jacoby/perl/ch-1.pl new file mode 100644 index 0000000000..44ecb815d1 --- /dev/null +++ b/challenge-268/dave-jacoby/perl/ch-1.pl @@ -0,0 +1,46 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use experimental qw{ fc postderef say signatures state }; + +use List::Util qw{ uniq any }; + +my @examples = ( + + [ [ 3, 7, 5 ], [ 9, 5, 7 ], ], + [ [ 1, 2, 1 ], [ 5, 4, 4 ], ], + [ [2], [5], ], +); + +for my $example (@examples) { + my $output = find_magic_number(@$example); + my $x = join ',', $example->[0]->@*; + my $y = join ',', $example->[1]->@*; + say <<"END"; + Input: \@x = ($x) + \@y = ($y) + Output: $output +END +} + +sub find_magic_number (@arrays) { + my ( $x, $y ) = @arrays; + my %hash; + my %o; + my @n; + for my $v ( $x->@* ) { + my @o = map { abs $v - $_ } $y->@*; + $hash{$v}->@* = @o; + push @n, @o; + } + for my $v ( uniq sort @n ) { + my $c = 0; + for my $k ( keys %hash ) { + $c++ if any { $v == $_ } $hash{$k}->@*; + } + $o{$v} = $c; + } + my @o = sort { $o{$b} <=> $o{$a} } keys %o; + return shift @o; +} diff --git a/challenge-268/dave-jacoby/perl/ch-2.pl b/challenge-268/dave-jacoby/perl/ch-2.pl new file mode 100644 index 0000000000..f11acbc962 --- /dev/null +++ b/challenge-268/dave-jacoby/perl/ch-2.pl @@ -0,0 +1,38 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use experimental qw{ fc say postderef signatures state }; + +use List::Util qw{ first }; + +my @examples = ( + + [ 2, 5, 3, 4 ], + [ 9, 4, 1, 3, 6, 4, 6, 1 ], + [ 1, 2, 2, 3 ], +); + +for my $example (@examples) { + my @output = number_game( $example->@* ); + my $output = join ', ', @output; + my $ints = join ', ', $example->@*; + + say <<"END"; + Input: \@ints = ($ints) + Output: ($output) +END +} + +sub number_game (@ints) { + my @sorted = sort { $a <=> $b } @ints; + my @output; + while (@sorted) { + my @cache; + push @cache, shift @sorted; + push @cache, shift @sorted; + @cache = reverse @cache; + push @output, @cache; + } + return @output; +} -- cgit