perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 323 - Task 2: Tax Amount

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-323/#TASK2
 3 #
 4 # Task 2: Tax Amount
 5 # ==================
 6 #
 7 # You are given an income amount and tax brackets.
 8 #
 9 # Write a script to calculate the total tax amount.
10 #
11 ## Example 1
12 ##
13 ## Input: $income = 10, @tax = ([3, 50], [7, 10], [12,25])
14 ## Output: 2.65
15 ##
16 ## 1st tax bracket upto  3, tax is 50%.
17 ## 2nd tax bracket upto  7, tax is 10%.
18 ## 3rd tax bracket upto 12, tax is 25%.
19 ##
20 ## Total Tax => (3 * 50/100) + (4 * 10/100) + (3 * 25/100)
21 ##           => 1.50 + 0.40 + 0.75
22 ##           => 2.65
23 #
24 #
25 ## Example 2
26 ##
27 ## Input: $income = 2, @tax = ([1, 0], [4, 25], [5,50])
28 ## Output: 0.25
29 ##
30 ## Total Tax => (1 * 0/100) + (1 * 25/100)
31 ##           => 0 + 0.25
32 ##           => 0.25
33 #
34 #
35 ## Example 3
36 ##
37 ## Input: $income = 0, @tax = ([2, 50])
38 ## Output: 0
39 #
40 ############################################################
41 ##
42 ## discussion
43 ##
44 ############################################################
45 #
46 # First of all, there is no indication what should happen once
47 # all tax brackets have been used up. I'm going to assume the tax
48 # is zero in that case.
49 # Then we just check each bracket, always keeping track of the previous
50 # bracket to know how big the part will be for the current bracket,
51 # and calculate the tax.
52 
53 use v5.36;
54 
55 tax_amount(10, [3, 50], [7, 10], [12,25]);
56 tax_amount(2, [1, 0], [4, 25], [5,50]);
57 tax_amount(0, [2, 50]);
58 tax_amount(5, [2, 50]);
59 
60 sub tax_amount($income, @tax) {
61     say "Income: $income";
62     print "Tax brackets: (";
63     foreach my $t (@tax) {
64         print "[$t->[0], $t->[1]], ";
65     }
66     say ")";
67     my $tax = 0;
68     my $previous = 0;
69     foreach my $t (@tax) {
70         my $end = $t->[0];
71         my $percent = $t->[1];
72         if($income <= $end) {
73             $tax += ($income - $previous) * $percent / 100;
74             last;
75         } else {
76             $tax += ($end - $previous) * $percent / 100;
77             $previous = $end;
78         }
79     }
80     say "Output: $tax";
81 }