Skip to content

Instantly share code, notes, and snippets.

@kevincolyer
Created November 8, 2019 12:38
Show Gist options
  • Save kevincolyer/0083c27df3a46e6bbb2af8f1edee2da6 to your computer and use it in GitHub Desktop.
Save kevincolyer/0083c27df3a46e6bbb2af8f1edee2da6 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl6
use v6;
use Test;
=begin pod
Task 33.1
Count Letters (A..Z)
Create a script that accepts one or more files specified on the command-line and count the number of times letters appeared in the files.
So with the following input file sample.txt
The quick brown fox jumps over the lazy dog.
the script would display something like:
a: 1
b: 1
c: 1
d: 1
e: 3 etc.
=end pod
sub count($text) {
return BagHash.new( $text.lc.comb.grep: * ~~ / <alpha> / );
}
multi MAIN(*@files) {
my BagHash $bag;
for @files -> $f {
next unless $f.IO:f;
$bag{.key}+=.value for count($f.IO.slurp); # Add returned bag to bag hash
}
$bag{"_"}:delete;
say "$_: {$bag{$_}}" for $bag.keys.collate;
}
multi MAIN("test") {
my $i=BagHash.new(<a b b>);
my $j=BagHash.new(<á b b>);
is-deeply count("abb"),$i,"test counts";
is-deeply count("Abb"),$i,"test lowercase";
is-deeply count("Ább"),$j,"test lowercase2";
is-deeply count("a 1 b\n.b!"),$i,"test not counting non-words";
}
#!/usr/bin/perl6
use v6;
=begin pod
Task 33.2
Formatted Multiplication Table
Write a script to print 11x11 multiplication table, only the top half triangle.
x| 1 2 3 4 5 6 7 8 9 10 11
---+--------------------------------------------
1| 1 2 3 4 5 6 7 8 9 10 11
2| 4 6 8 10 12 14 16 18 20 22
3| 9 12 15 18 21 24 27 30 33
4| 16 20 24 28 32 36 40 44
5| 25 30 35 40 45 50 55
6| 36 42 48 54 60 66
7| 49 56 63 70 77
8| 64 72 80 88
9| 81 90 99
10| 100 110
11| 121
=end pod
sub MAIN($table=11) {
# header
print " x|";
print frmt($_) for 1..$table;
print "\n";
print "---+";
say "----" x $table;
# body
for 1..$table -> $i {
print frmt($i,3) ~ "|";
print " " for 1..$i-1;
print frmt($i*$_) for $i..$table;
print "\n";
}
}
sub frmt($i, $pad=4, --> Str) {
return sprintf("%{$pad}s",$i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment