perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 311 - Task 2: Group Digit Sum

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-311/#TASK2
 3 #
 4 # Task 2: Group Digit Sum
 5 # =======================
 6 #
 7 # You are given a string, $str, made up of digits, and an integer, $int, which is less than the length of the given string.
 8 #
 9 # Write a script to divide the given string into consecutive groups of size $int
10 # (plus one for leftovers if any). Then sum the digits of each group, and
11 # concatenate all group sums to create a new string. If the length of the new
12 # string is less than or equal to the given integer then return the new string,
13 # otherwise continue the process.
14 #
15 ## Example 1
16 ##
17 ## Input: $str = "111122333", $int = 3
18 ## Output: "359"
19 ##
20 ## Step 1: "111", "122", "333" => "359"
21 #
22 ## Example 2
23 ##
24 ## Input: $str = "1222312", $int = 2
25 ## Output: "76"
26 ##
27 ## Step 1: "12", "22", "31", "2" => "3442"
28 ## Step 2: "34", "42" => "76"
29 #
30 ## Example 3
31 ##
32 ## Input: $str = "100012121001", $int = 4
33 ## Output: "162"
34 ##
35 ## Step 1: "1000", "1212", "1001" => "162"
36 #
37 ############################################################
38 ##
39 ## discussion
40 ##
41 ############################################################
42 #
43 # As long as $str is bigger than $int, do a loop:
44 # - split $str into its parts, store those in a temporary array
45 # - calculate the sum of digits for each of those parts, store
46 #   those sums into another temporary array
47 # - concatenate those sums, forming the new $str
48 # - repeat until the length of $str <= $int
49 # - return the result
50 
51 use v5.36;
52 use List::Util qw(sum);
53 
54 group_digit_sum("111122333", 3);
55 group_digit_sum("1222312", 2);
56 group_digit_sum("100012121001", 4);
57 
58 
59 sub group_digit_sum($str, $int) {
60    say "Input: \$str = \"$str\", \$int = $int";
61    my $sum = 0;
62    while(length($str) > $int) {
63       my @tmp = ();
64       while(length($str) > $int) {
65          push @tmp, substr($str, 0, $int);
66          $str = substr($str, $int);
67       }
68       push @tmp, $str;
69       my @sums = ();
70       foreach my $elem (@tmp) {
71          my @parts = split//, $elem;
72          push @sums, sum(@parts);
73       }
74       $str = join("", @sums);
75    }
76    say "Output: $str";
77 }