From 625e5ddc739847e008f5798c9573487924bedcd0 Mon Sep 17 00:00:00 2001 From: Dave Jacoby Date: Sun, 9 Aug 2020 23:18:24 -0400 Subject: Challenge 73 --- challenge-073/dave-jacoby/perl/ch-1.pl | 49 ++++++++++++++++++++++++++++++++++ challenge-073/dave-jacoby/perl/ch-2.pl | 28 +++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100755 challenge-073/dave-jacoby/perl/ch-1.pl create mode 100755 challenge-073/dave-jacoby/perl/ch-2.pl diff --git a/challenge-073/dave-jacoby/perl/ch-1.pl b/challenge-073/dave-jacoby/perl/ch-1.pl new file mode 100755 index 0000000000..a9a16cfa67 --- /dev/null +++ b/challenge-073/dave-jacoby/perl/ch-1.pl @@ -0,0 +1,49 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use feature qw{ say signatures state }; +no warnings qw{ experimental }; + +use List::Util qw{ min }; + +# You are given an array of integers @A and sliding window size $S. + +# Write a script to create an array of min from each sliding window. + +# Example +# Input: @A = (1, 5, 0, 2, 9, 3, 7, 6, 4, 8) and $S = 3 +# Output: (0, 0, 0, 2, 3, 3, 4, 4) + +# [(1 5 0) 2 9 3 7 6 4 8] = Min (0) +# [1 (5 0 2) 9 3 7 6 4 8] = Min (0) +# [1 5 (0 2 9) 3 7 6 4 8] = Min (0) +# [1 5 0 (2 9 3) 7 6 4 8] = Min (2) +# [1 5 0 2 (9 3 7) 6 4 8] = Min (3) +# [1 5 0 2 9 (3 7 6) 4 8] = Min (3) +# [1 5 0 2 9 3 (7 6 4) 8] = Min (4) +# [1 5 0 2 9 3 7 (6 4 8)] = Min (4) + +my @array = ( 1, 5, 0, 2, 9, 3, 7, 6, 4, 8 ); +my $s = 3; + +sliding_window( $s, \@array ); + +sub sliding_window ( $s, $arr ) { + my @arr = $arr->@*; + my $max_n = $#arr; + + for my $n ( 0 .. $#arr ) { + next if $n + 2 > $max_n; + my $min = min map { $arr[$_] } $n .. $n + 2; + + print '['; + for my $i ( 0 .. $#arr ) { + print $i == $n ? '(' : ' '; + print $arr[$i]; + print $i == $n +2 ? ')' : ' '; + } + say qq{] = Min ($min)}; + } +} + diff --git a/challenge-073/dave-jacoby/perl/ch-2.pl b/challenge-073/dave-jacoby/perl/ch-2.pl new file mode 100755 index 0000000000..0c66b7ccfe --- /dev/null +++ b/challenge-073/dave-jacoby/perl/ch-2.pl @@ -0,0 +1,28 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use feature qw{ say signatures state }; +no warnings qw{ experimental }; + +use List::Util qw{min}; + +smallest_neighbour( 7, 8, 3, 12, 10 ); +smallest_neighbour( 4, 6, 5 ); +smallest_neighbour( map { 1 + int rand 15 } 0 .. 2 + int rand 10 ); + +sub smallest_neighbour ( @array ) { + my @output; + my @left; + + say join "\t", 'INPUT: ', join ', ', @array; + while (@array) { + my $k = shift @array; + my $l = min grep { $_ < $k } @left; + push @output, defined $l ? $l : 0; + push @left, $k; + } + + say join "\t", 'OUTPUT: ', join ', ', @output; + say ''; +} -- cgit