Created
April 30, 2024 17:17
-
-
Save nd3i/b10f39060b706912ee7cb07c8fb41576 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Task 2: Line Counts | |
# | |
# You are given a string, $str, and a 26-items array @widths | |
# containing the width of each character from a to z. | |
# | |
# Write a script to find out the number of lines and the width of the | |
# last line needed to display the given string, assuming you can only | |
# fit 100 width units on a line. | |
constant $width = 100; | |
sub wrap($str, @widths) { | |
my %wtbl = (('a'..'z') Z @widths)>>.pairup.flat; # build width table | |
my $lw = 0; | |
my $line = ''; | |
gather { | |
for $str.comb -> $c { | |
my $cw = %wtbl{$c}; | |
if $width-$lw < $cw { | |
take $lw.clone, $line.clone; | |
$lw = 0; | |
$line = ''; | |
} | |
$lw += $cw; | |
$line ~= $c; | |
} | |
take $lw.clone, $line.clone if $line.chars; | |
} | |
} | |
-> $s, @w { | |
my @lines = wrap($s, @w); | |
say @lines | |
} for | |
# Example 1 | |
'abcdefghijklmnopqrstuvwxyz', | |
(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), | |
# Output: (3, 60) | |
# Line 1: abcdefghij (100 pixels) | |
# Line 2: klmnopqrst (100 pixels) | |
# Line 3: uvwxyz (60 pixels) | |
# Example 2 | |
'bbbcccdddaaa', | |
( 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), | |
# Output: (2, 4) | |
# Line 1: bbbcccdddaa (98 pixels) | |
# Line 2: a (4 pixels) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment