aboutsummaryrefslogtreecommitdiff
path: root/challenge-327
diff options
context:
space:
mode:
authorwanderdoc <wanderdoc@users.noreply.github.com>2025-06-29 17:15:17 +0200
committerGitHub <noreply@github.com>2025-06-29 17:15:17 +0200
commitb54bbc71289fcd7fd6a4bc4f7ff88a68215a016e (patch)
treef13ffd8ead82ae135b2bdd9387507c5c650d9bcf /challenge-327
parent73f1070944ee9169cd9b56a85dcfeba6d9aa1ebf (diff)
downloadperlweeklychallenge-club-b54bbc71289fcd7fd6a4bc4f7ff88a68215a016e.tar.gz
perlweeklychallenge-club-b54bbc71289fcd7fd6a4bc4f7ff88a68215a016e.tar.bz2
perlweeklychallenge-club-b54bbc71289fcd7fd6a4bc4f7ff88a68215a016e.zip
Create ch-2.pl
Diffstat (limited to 'challenge-327')
-rw-r--r--challenge-327/wanderdoc/perl/ch-2.pl62
1 files changed, 62 insertions, 0 deletions
diff --git a/challenge-327/wanderdoc/perl/ch-2.pl b/challenge-327/wanderdoc/perl/ch-2.pl
new file mode 100644
index 0000000000..3ede1b1a0c
--- /dev/null
+++ b/challenge-327/wanderdoc/perl/ch-2.pl
@@ -0,0 +1,62 @@
+#!perl
+use strict;
+use warnings FATAL => qw(all);
+
+=prompt
+You are given an array of distinct integers.
+Write a script to find all pairs of elements with minimum absolute difference (MAD) of any two elements.
+
+Example 1
+
+Input: @ints = (4, 1, 2, 3)
+Output: [1,2], [2,3], [3,4]
+
+The minimum absolute difference is 1.
+Pairs with MAD: [1,2], [2,3], [3,4]
+
+
+Example 2
+
+Input: @ints = (1, 3, 7, 11, 15)
+Output: [1,3]
+
+
+Example 3
+
+Input: @ints = (1, 5, 3, 8)
+Output: [1,3], [3,5]
+
+
+=cut
+
+
+use Test2::V0 -no_srand => 1;
+
+is([min_abs_diff(4, 1, 2, 3)], [[1,2], [2,3], [3,4]], 'Example 1');
+is([min_abs_diff(1, 3, 7, 11, 15)], [[1,3]], 'Example 2');
+is([min_abs_diff(1, 5, 3, 8)], [[1,3], [3,5]], 'Example 3');
+done_testing();
+
+
+
+sub min_abs_diff
+{
+ my @arr = @_;
+ @arr = sort { $a <=> $b } @arr;
+ my @output;
+ my $min_diff = ~0+1;
+ for my $idx ( 0 .. $#arr-1 )
+ {
+ if ( ($arr[$idx+1] - $arr[$idx]) < $min_diff )
+ {
+ @output = ();
+ push @output, [$arr[$idx], $arr[$idx+1]];
+ $min_diff = $arr[$idx+1] - $arr[$idx]
+ }
+ elsif (($arr[$idx+1] - $arr[$idx]) == $min_diff)
+ {
+ push @output, [$arr[$idx], $arr[$idx+1]];
+ }
+ }
+ return @output;
+}