perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 351 - Task 2: Arithmetic Progression

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-351/#TASK2
 3 #
 4 # Task 2: Arithmetic Progression
 5 # ==============================
 6 #
 7 # You are given an array of numbers.
 8 #
 9 # Write a script to return true if the given array can be re-arranged to form
10 # an arithmetic progression, otherwise return false.
11 #
12 ### A sequence of numbers is called an arithmetic progression if the difference
13 ### between any two consecutive elements is the same.
14 #
15 ## Example 1
16 ##
17 ## Input: @num = (1, 3, 5, 7, 9)
18 ## Output: true
19 ##
20 ## Already AP with common difference 2.
21 #
22 #
23 ## Example 2
24 ##
25 ## Input: @num = (9, 1, 7, 5, 3)
26 ## Output: true
27 ##
28 ## The given array re-arranged like (1, 3, 5, 7, 9) with common difference 2.
29 #
30 #
31 ## Example 3
32 ##
33 ## Input: @num = (1, 2, 4, 8, 16)
34 ## Output: false
35 ##
36 ## This is geometric progression and not arithmetic progression.
37 #
38 #
39 ## Example 4
40 ##
41 ## Input: @num = (5, -1, 3, 1, -3)
42 ## Output: true
43 ##
44 ## The given array re-arranged like (-3, -1, 1, 3, 5) with common difference 2.
45 #
46 #
47 ## Example 5
48 ##
49 ## Input: @num = (1.5, 3, 0, 4.5, 6)
50 ## Output: true
51 ##
52 ## The given array re-arranged like (0, 1.5, 3, 4.5, 6) with common difference 1.5.
53 #
54 ############################################################
55 ##
56 ## discussion
57 ##
58 ############################################################
59 #
60 # We need to sort the elements to check whether they form an arithmetic
61 # progression. Then we check whether the difference of two subsequent
62 # numbers is always the same.
63 
64 use v5.36;
65 
66 arithmetic_progression(1, 3, 5, 7, 9);
67 arithmetic_progression(9, 1, 7, 5, 3);
68 arithmetic_progression(1, 2, 4, 8, 16);
69 arithmetic_progression(5, -1, 3, 1, -3);
70 arithmetic_progression(1.5, 3, 0, 4.5, 6);
71 
72 sub arithmetic_progression(@num) {
73     say "Input: (" . join(", ", @num) . ")";
74     my @sorted = sort { $a <=> $b } @num;
75     my $diff = $sorted[1] - $sorted[0];
76     foreach my $index (0..$#sorted-1) {
77         if($sorted[$index+1] - $sorted[$index] != $diff) {
78             return say "Output: false";
79         }
80     }
81     say "Output: true";
82 }