perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 323 - Task 1: Increment Decrement

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-323/#TASK1
 3 #
 4 # Task 1: Increment Decrement
 5 # ===========================
 6 #
 7 # You are given a list of operations.
 8 #
 9 # Write a script to return the final value after performing the given
10 # operations in order. The initial value is always 0.
11 #
12 # Possible Operations:
13 # ++x or x++: increment by 1
14 # --x or x--: decrement by 1
15 #
16 #
17 ## Example 1
18 ##
19 ## Input: @operations = ("--x", "x++", "x++")
20 ## Output: 1
21 ##
22 ## Operation "--x" =>  0 - 1 => -1
23 ## Operation "x++" => -1 + 1 =>  0
24 ## Operation "x++" =>  0 + 1 =>  1
25 #
26 #
27 ## Example 2
28 ##
29 ## Input: @operations = ("x++", "++x", "x++")
30 ## Output: 3
31 #
32 #
33 ## Example 3
34 ##
35 ## Input: @operations = ("x++", "++x", "--x", "x--")
36 ## Output: 0
37 ##
38 ## Operation "x++" => 0 + 1 => 1
39 ## Operation "++x" => 1 + 1 => 2
40 ## Operation "--x" => 2 - 1 => 1
41 ## Operation "x--" => 1 - 1 => 0
42 #
43 ############################################################
44 ##
45 ## discussion
46 ##
47 ############################################################
48 #
49 # Each possible input maps to either +1 or -1, so we just
50 # fill a hash with those possible inputs as keys and their
51 # corresponding mappings as values. Then we just need to
52 # add up all the values for all given operations.
53 
54 use v5.36;
55 
56 increment_decrement("--x", "x++", "x++");
57 increment_decrement("x++", "++x", "x++");
58 increment_decrement("x++", "++x", "--x", "x--");
59 
60 sub increment_decrement( @operations ) {
61     say "Input: (\"" . join("\", \"", @operations) . "\")";
62     my $value = 0;
63     my $add = {
64         "++x" => 1,
65         "x++" => 1,
66         "--x" => -1,
67         "x--" => -1,
68     };
69     foreach my $op (@operations) {
70         $value += $add->{$op};
71     }
72     say "Output: $value";
73 }