|
| 1 | +#!/usr/bin/perl |
| 2 | + |
| 3 | +use v5.26; |
| 4 | +use Test2::V0 qw(!float -no_srand); |
| 5 | +use Test2::Tools::Subtest 'subtest_streamed'; |
| 6 | +use Getopt::Long; |
| 7 | +use experimental 'signatures'; |
| 8 | + |
| 9 | +use PDL; |
| 10 | + |
| 11 | +### Options and Arguments |
| 12 | + |
| 13 | +my ($tests, $examples, $verbose, $len); |
| 14 | +GetOptions( |
| 15 | + 'examples!' => \$examples, |
| 16 | + 'tests!' => \$tests, |
| 17 | + 'verbose!' => \$verbose, |
| 18 | +) or usage(); |
| 19 | + |
| 20 | +run_tests($examples, $tests); # tests do not return |
| 21 | + |
| 22 | +usage() unless @ARGV == 2; |
| 23 | + |
| 24 | +sub usage { |
| 25 | + die <<~EOS; |
| 26 | + $0 - Group digit sum |
| 27 | +
|
| 28 | + usage: $0 [-examples] [-tests] [S I] |
| 29 | +
|
| 30 | + -examples |
| 31 | + run the examples from the challenge |
| 32 | + |
| 33 | + -tests |
| 34 | + run some tests |
| 35 | +
|
| 36 | + S |
| 37 | + a number |
| 38 | +
|
| 39 | + I |
| 40 | + group length |
| 41 | +
|
| 42 | + EOS |
| 43 | +} |
| 44 | + |
| 45 | + |
| 46 | +### Input and Output |
| 47 | + |
| 48 | +say group_digit_sum(@ARGV); |
| 49 | + |
| 50 | + |
| 51 | +### Implementation |
| 52 | +# |
| 53 | +# For details see: |
| 54 | +# https://github.sommrey.de/the-bears-den/2025/03/07/ch-311.html#task-2 |
| 55 | + |
| 56 | + |
| 57 | +sub group_digit_sum ($str, $len) { |
| 58 | + my $n = long split //, $str; |
| 59 | + $n = long map split(//, $_), |
| 60 | + $n->reshape($len, ceil $n->dim(0) / $len)->sumover->list |
| 61 | + while $n->dim(0) > $len; |
| 62 | + join '', $n->list; |
| 63 | +} |
| 64 | + |
| 65 | + |
| 66 | +### Examples and Tests |
| 67 | + |
| 68 | +sub run_tests ($examples, $tests) { |
| 69 | + return unless $examples || $tests; |
| 70 | + |
| 71 | + state sub run_example ($args, $expected, $name) { |
| 72 | + my $result = group_digit_sum(@$args); |
| 73 | + is $result, $expected, |
| 74 | + "$name: (@$args) -> $expected"; |
| 75 | + } |
| 76 | + |
| 77 | + plan 2; |
| 78 | + |
| 79 | + $examples ? subtest_streamed(examples => sub { |
| 80 | + my @examples = ( |
| 81 | + [[111122333, 3], 359, 'example 1'], |
| 82 | + [[1222312, 2], 76, 'example 2'], |
| 83 | + [[100012121001, 4], 162, 'example 3'], |
| 84 | + ); |
| 85 | + plan scalar @examples; |
| 86 | + for (@examples) { |
| 87 | + run_example @$_; |
| 88 | + } |
| 89 | + }) : pass 'skip examples'; |
| 90 | + |
| 91 | + $tests ? subtest_streamed(tests => sub { |
| 92 | + plan 3; |
| 93 | + is group_digit_sum(9999, 2), 99, 'carry'; |
| 94 | + is group_digit_sum(999999999, 3), 36, 'multiple loops'; |
| 95 | + is group_digit_sum('9' x 320, 40), '360' x 8, 'exceed longlong'; |
| 96 | + }) : pass 'skip tests'; |
| 97 | + |
| 98 | + exit; |
| 99 | +} |
0 commit comments