From b1beb66bad02cf5c1bb1793c4590acb062b17298 Mon Sep 17 00:00:00 2001 From: Dave Jacoby Date: Thu, 6 Feb 2025 20:43:51 -0500 Subject: Didn't I do 306? --- challenge-306/dave-jacoby/perl/ch-1.pl | 36 +++++++++++++++++++++++++ challenge-306/dave-jacoby/perl/ch-2.pl | 49 ++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 challenge-306/dave-jacoby/perl/ch-1.pl create mode 100644 challenge-306/dave-jacoby/perl/ch-2.pl diff --git a/challenge-306/dave-jacoby/perl/ch-1.pl b/challenge-306/dave-jacoby/perl/ch-1.pl new file mode 100644 index 0000000000..901dffcdff --- /dev/null +++ b/challenge-306/dave-jacoby/perl/ch-1.pl @@ -0,0 +1,36 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use experimental qw{ say state postderef signatures }; + +use List::Util qw{ sum0 }; + +my @examples = ( + + [ 2, 5, 3, 6, 4 ], + [ 1, 3 ], +); + +for my $example (@examples) { + my $ints = join ', ', $example->@*; + my $output = odd_sum( $example->@* ); + say <<"END"; + Input: \@ints = ($ints) + Output: $output +END +} + +sub odd_sum(@ints) { + my $output; + for my $l ( map { $_ * 2 - 1 } 1 .. $#ints ) { + next if $l > scalar @ints; + for my $i ( 0 .. $#ints ) { + my $end = -1 + $i + $l; + next unless defined $ints[$end]; + my @slice = @ints[ $i .. $end ]; + $output += sum0(@slice); + } + } + return $output; +} diff --git a/challenge-306/dave-jacoby/perl/ch-2.pl b/challenge-306/dave-jacoby/perl/ch-2.pl new file mode 100644 index 0000000000..fed124329b --- /dev/null +++ b/challenge-306/dave-jacoby/perl/ch-2.pl @@ -0,0 +1,49 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use experimental qw{ say state postderef signatures }; + +use List::Util qw{ first }; + +my @examples = ( + + [ 3, 8, 5, 2, 9, 2 ], + [ 3, 2, 5 ], +); + +for my $example (@examples) { + my $ints = join ', ', $example->@*; + my $output = last_element( $example->@* ); + say <<"END"; + Input: \@ints = ($ints) + Output: $output +END +} + +sub last_element(@ints) { + while ( scalar @ints > 1 ) { + my ( $y, $x ) = sort { $b <=> $a } @ints; + if ( $x == $y ) { + # there's ugly enough that, if I was to rewrite this, + # I would separate this into a function, probably. + # As a one-off, it isn't worth it. + my $ix = first { $ints[$_] == $x } 0 .. $#ints; + $ints[$ix] = undef; + @ints = grep { defined } @ints; + my $iy = first { $ints[$_] == $y } 0 .. $#ints; + $ints[$iy] = undef; + @ints = grep { defined } @ints; + } + else { + my $yx = $y - $x; + my $iy = first { $ints[$_] == $y } 0 .. $#ints; + $ints[$iy] = undef; + @ints = grep { defined } @ints; + my $ix = first { $ints[$_] == $x } 0 .. $#ints; + $ints[$ix] = $yx; + @ints = grep { defined } @ints; + } + } + return scalar @ints; +} -- cgit