Up, down, and pay your tax
Weekly challenge 323 — 26 May 2025
Week 323: 26 May 2025
You are given a list of operations. Write a script to return the final value after performing the given operations in order. The initial value is always 0.
Possible operations:
Example 1 Input: @operations = ('--x', 'x++', 'x++') Output: 1 Operation '--x' => 0 - 1 => -1 Operation 'x++' => -1 + 1 => 0 Operation 'x++' => 0 + 1 => 1 Example 2 Input: @operations = ('x++', '++x', 'x++') Output: 3 Example 3 Input: @operations = ('x++', '++x', '--x', 'x--') Output: 0 Operation 'x++' => 0 + 1 => 1 Operation '++x' => 1 + 1 => 2 Operation '--x' => 2 - 1 => 1 Operation 'x--' => 1 - 1 => 0
My solution is very simple.
First let's assume that all the operations are 'subtract 1'. So the total is
simply minus the number of elements in @operations
.
Now let's look for elements that contain '+'. For each of these we add 2 to the total: 1 to cancel out having erroneously assumed it was a 'subtract 1' and 1 to record the fact that it is an 'add 1'.
And that's the answer.
In 'real life' I wouldn't accept that solution because we only have Mohammad's word for it that the elements are all one of the 4 possibilities he lists. Of course Mohammad is an honourable man and we can see that he has stuck to the rules in the three examples.
But in general, unless that conformance is guaranteed by earlier code in the same module I would check that each element is indeed one of the 4 documented values and raise an error if not.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-05-26 use utf8; # Week 323 - task 1 - Increment decrement use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; increment_decrement('--x', 'x++', 'x++'); increment_decrement('x++', '++x', 'x++'); increment_decrement('x++', '++x', '--x', 'x--'); sub increment_decrement { my (@operations, $result); # initialise @operations = @_; # assumw they are all negative $result = -@operations; # add 2 for each positive one $result += 2 for grep(/\+/, @operations); say qq[\nInput: ('] . join(q[', '], @operations) . q[')]; say qq[Output: $result]; }
Input: ('--x', 'x++', 'x++') Output: 1 Input: ('x++', '++x', 'x++') Output: 3 Input: ('x++', '++x', '--x', 'x--') Output: 0
Any content of this website which has been created by Peter Campbell Smith is in the public domain