diff options
| author | Lubos Kolouch <lubos@kolouch.net> | 2025-10-13 10:19:41 +0200 |
|---|---|---|
| committer | Lubos Kolouch <lubos@kolouch.net> | 2025-10-13 10:19:41 +0200 |
| commit | 4781aa70debbc13c1be52b833bfb6ccb8a9b16c3 (patch) | |
| tree | 820c183ab5e485c8ab5a1040ab41c534019dd40f | |
| parent | 35a27e16cb743acd46c1f315766530dc991ac587 (diff) | |
| download | perlweeklychallenge-club-4781aa70debbc13c1be52b833bfb6ccb8a9b16c3.tar.gz perlweeklychallenge-club-4781aa70debbc13c1be52b833bfb6ccb8a9b16c3.tar.bz2 perlweeklychallenge-club-4781aa70debbc13c1be52b833bfb6ccb8a9b16c3.zip | |
Challenge 343 Task 1 Perl LK
| -rw-r--r-- | challenge-343/lubos-kolouch/perl/ch-1.pl | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/challenge-343/lubos-kolouch/perl/ch-1.pl b/challenge-343/lubos-kolouch/perl/ch-1.pl new file mode 100644 index 0000000000..0d670fa61d --- /dev/null +++ b/challenge-343/lubos-kolouch/perl/ch-1.pl @@ -0,0 +1,39 @@ +#!/usr/bin/env perl + +# Perl Weekly Challenge: Task 1 - Zero Friend +# Find the number closest to zero and return its distance to zero. + +use strict; +use warnings; +use v5.30; + +# Type definitions (using experimental Perl features for clarity) +use experimental 'signatures'; + +# Function to find the distance to zero of the closest number +sub zero_friend : prototype(@) (@nums) { + + # Return 0 if the input is empty + return 0 unless @nums; + + # Find the minimum absolute value + my $min_distance = abs( $nums[0] ); + for my $num (@nums) { + my $distance = abs($num); + $min_distance = $distance if $distance < $min_distance; + } + + return $min_distance; +} + +# Unit tests +use Test::More; + +# Test cases from the problem +is( zero_friend( 4, 2, -1, 3, -2 ), 1, 'Test Case 1: (4, 2, -1, 3, -2) -> 1' ); +is( zero_friend( -5, 5, -3, 3, -1, 1 ), 1, 'Test Case 2: (-5, 5, -3, 3, -1, 1) -> 1' ); +is( zero_friend( 7, -3, 0, 2, -8 ), 0, 'Test Case 3: (7, -3, 0, 2, -8) -> 0' ); +is( zero_friend( -2, -5, -1, -8 ), 1, 'Test Case 4: (-2, -5, -1, -8) -> 1' ); +is( zero_friend( -2, 2, -4, 4, -1, 1 ), 1, 'Test Case 5: (-2, 2, -4, 4, -1, 1) -> 1' ); + +done_testing(); |
