|
| 1 | +#!/usr/bin/env perl |
| 2 | +# |
| 3 | +=head1 Task 2: Group Digit Sum |
| 4 | +
|
| 5 | +Submitted by: Mohammad Sajid Anwar |
| 6 | +
|
| 7 | +You are given a string, $str, made up of digits, and an integer, $int, which is |
| 8 | +less than the length of the given string. |
| 9 | +
|
| 10 | +Write a script to divide the given string into consecutive groups of size $int |
| 11 | +(plus one for leftovers if any). Then sum the digits of each group, and |
| 12 | +concatenate all group sums to create a new string. If the length of the new |
| 13 | +string is less than or equal to the given integer then return the new string, |
| 14 | +otherwise continue the process. |
| 15 | +
|
| 16 | +=head2 Example 1 |
| 17 | +
|
| 18 | + Input: $str = "111122333", $int = 3 |
| 19 | + Output: "359" |
| 20 | +
|
| 21 | + Step 1: "111", "122", "333" => "359" |
| 22 | +
|
| 23 | +=head2 Example 2 |
| 24 | +
|
| 25 | + Input: $str = "1222312", $int = 2 |
| 26 | + Output: "76" |
| 27 | +
|
| 28 | + Step 1: "12", "22", "31", "2" => "3442" |
| 29 | + Step 2: "34", "42" => "76" |
| 30 | +
|
| 31 | +=head2 Example 3 |
| 32 | +
|
| 33 | + Input: $str = "100012121001", $int = 4 |
| 34 | + Output: "162" |
| 35 | +
|
| 36 | + Step 1: "1000", "1212", "1001" => "162" |
| 37 | +
|
| 38 | +=cut |
| 39 | + |
| 40 | +use strict; |
| 41 | +use warnings; |
| 42 | +use Test2::V0 -no_srand => 1; |
| 43 | +use Data::Dumper; |
| 44 | +use List::Util qw(sum0); |
| 45 | + |
| 46 | +my $cases = [ |
| 47 | + [["111122333", 3], 359, "Example 1"], |
| 48 | + [["1222312", 2], 76, "Example 2"], |
| 49 | + [["100012121001", 4], 162, "Example 3"], |
| 50 | +]; |
| 51 | + |
| 52 | +sub group_digit_sum |
| 53 | +{ |
| 54 | + my $str = $_[0]->[0]; |
| 55 | + my $int = $_[0]->[1]; |
| 56 | + |
| 57 | + my $new_str; |
| 58 | + while (length($str) > $int) { |
| 59 | + $new_str = ''; |
| 60 | + for (my $i = 0; $i < length($str); $i += $int) { |
| 61 | + my $s = substr($str, $i, $int); |
| 62 | + $new_str .= sum0 split(//, $s); |
| 63 | + } |
| 64 | + $str = $new_str; |
| 65 | + } |
| 66 | + return $new_str; |
| 67 | +} |
| 68 | + |
| 69 | +for (@$cases) { |
| 70 | + is(group_digit_sum($_->[0]), $_->[1], $_->[2]); |
| 71 | +} |
| 72 | +done_testing(); |
| 73 | + |
| 74 | +exit 0; |
0 commit comments