perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 343 - Task 1: Zero Friend

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-343/#TASK1
 3 #
 4 # Task 1: Zero Friend
 5 # ===================
 6 #
 7 # You are given a list of numbers.
 8 #
 9 # Find the number that is closest to zero and return its distance to zero.
10 #
11 ## Example 1
12 ##
13 ## Input: @nums = (4, 2, -1, 3, -2)
14 ## Output: 1
15 ##
16 ## Values closest to 0: -1 and 2 (distance = 1 and 2)
17 #
18 #
19 ## Example 2
20 ##
21 ## Input: @nums = (-5, 5, -3, 3, -1, 1)
22 ## Output: 1
23 ##
24 ## Values closest to 0: -1 and 1 (distance = 1)
25 #
26 #
27 ## Example 3
28 ##
29 ## Input: @ums = (7, -3, 0, 2, -8)
30 ## Output: 0
31 ##
32 ## Values closest to 0: 0 (distance = 0)
33 ## Exact zero wins regardless of other close values.
34 #
35 #
36 ## Example 4
37 ##
38 ## Input: @nums = (-2, -5, -1, -8)
39 ## Output: 1
40 ##
41 ## Values closest to 0: -1 and -2 (distance = 1 and 2)
42 #
43 #
44 ## Example 5
45 ##
46 ## Input: @nums = (-2, 2, -4, 4, -1, 1)
47 ## Output: 1
48 ##
49 ## Values closest to 0: -1 and 1 (distance = 1)
50 #
51 ############################################################
52 ##
53 ## discussion
54 ##
55 ############################################################
56 #
57 # The distance to zero is exactly the absolute value of the number.
58 # So we just need to find the smallest absolute value in the array.
59 #
60 
61 use v5.36;
62 
63 zero_friend(4, 2, -1, 3, -2);
64 zero_friend(-5, 5, -3, 3, -1, 1);
65 zero_friend(7, -3, 0, 2, -8);
66 zero_friend(-2, -5, -1, -8);
67 zero_friend(-2, 2, -4, 4, -1, 1);
68 
69 sub zero_friend(@nums) {
70     say "Input: (" . join(", ", @nums) . ")";
71     my $result = abs($nums[0]);
72     foreach my $elem (@nums) {
73         $result = abs($elem) if abs($elem) < $result;
74     }
75     say "Output: $result";
76 }