-
Notifications
You must be signed in to change notification settings - Fork 311
/
ch-2.pl
65 lines (56 loc) · 1.56 KB
/
ch-2.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env perl
use strict;
use warnings;
use experimental qw{ fc say postderef signatures state };
use List::Util qw{sum0};
my @examples = (
{
str => "abcdefghijklmnopqrstuvwxyz",
widths => [
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10
]
},
{
str => "bbbcccdddaaa",
widths => [
4, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10
]
},
);
for my $example (@examples) {
my $str = $example->{str};
my @widths = $example->{widths}->@*;
my $widths = join ',', @widths;
my @output = line_counts($example);
my $output = join ', ', @output;
say <<"END";
Input: \$str = "$str"
\@widths = ($widths)
Output: ($output)
END
}
sub line_counts ($obj) {
my $str = $obj->{str};
my @widths = $obj->{widths}->@*;
my $sub = make_weight_function(@widths);
my $c = 1;
my $line = '';
for my $ch ( split //, $str ) {
my $cv = $sub->($ch);
my $lv = $sub->($line);
if ( $lv + $cv > 100 ) { $line = ''; $lv = $sub->($line); $c++; }
$line .= $ch;
}
return ( $c, $sub->($line) );
}
sub make_weight_function (@widths) {
my @alpha = 'a' .. 'z';
state $aw;
$aw->%* = map { $alpha[$_] => $widths[$_] } 0 .. 25;
return sub ($str) {
return sum0 map { $aw->{$_} } split //, $str;
};
return sub ($str) { return 1 };
}