From b87e9a24dd5b7e904babc5626f4874040cf58503 Mon Sep 17 00:00:00 2001 From: Util Date: Sun, 29 Oct 2023 15:56:59 -0500 Subject: Add TWC 240 solutions by Bruce Gray (Raku only). --- challenge-240/bruce-gray/raku/ch-1.raku | 48 +++++++++++++++++++++++++++++++++ challenge-240/bruce-gray/raku/ch-2.raku | 20 ++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 challenge-240/bruce-gray/raku/ch-1.raku create mode 100644 challenge-240/bruce-gray/raku/ch-2.raku diff --git a/challenge-240/bruce-gray/raku/ch-1.raku b/challenge-240/bruce-gray/raku/ch-1.raku new file mode 100644 index 0000000000..d94869d6f0 --- /dev/null +++ b/challenge-240/bruce-gray/raku/ch-1.raku @@ -0,0 +1,48 @@ +# Three solutions: +# Extract first letters of words, and join those letters, compare with FoldCase (.fc) . +# Use .starts-with to check each letter of the acronym against each word. +# Construct regex to match against the stringifiled list of words iff proper acronym. + +my sub first_letters ( @s --> Str ) { @s».substr(0, 1).join } + +sub task1_first_letters ( Str $acronym, @words --> Bool ) { + return $acronym.fc eq @words.&first_letters.fc; +} + + +# Used `Zsw` with size guard instead of `»sw«` to keep from throwing error. +my sub infix:«sw» { $^a.starts-with: $^b, :ignorecase } + +sub task1_starts_with ( Str $acronym, @words --> Bool ) { + return False if $acronym.chars != @words.elems; + + return ?all @words».fc Zsw $acronym.comb».fc; +} + + +sub task1_regex ( Str $acronym, @words --> Bool ) { + warn if @words.any ~~ /\s/; + + my $re = $acronym.comb.map( * ~ '\S*' ).join('\s+'); + + return so @words.Str ~~ m:i/ ^ <$re> $ /; +} + + +constant @tests = + ( True , ( 'ppp' , ) ), + ( False , ( 'rp' , ) ), + ( True , ( 'oac' , ) ), +; +constant @subs = + :&task1_first_letters, + :&task1_starts_with, + :&task1_regex, +; +use Test; plan @tests * @subs; +for @subs -> ( :key($sub_name), :value(&task1) ) { + for @tests -> ( Bool $expected, ( Str $acro, @words ) ) { + is task1($acro, @words), $expected, + "{$sub_name.fmt("%19s")} : $acro, @words[]"; + } +} diff --git a/challenge-240/bruce-gray/raku/ch-2.raku b/challenge-240/bruce-gray/raku/ch-2.raku new file mode 100644 index 0000000000..8261345f1a --- /dev/null +++ b/challenge-240/bruce-gray/raku/ch-2.raku @@ -0,0 +1,20 @@ +sub task2 ( Int @ns --> List ) { + + # if @ns.grep( * !~~ 0..@ns.end ) -> @bad { + # warn "These values are outside the range of possible keys, and so will be undefined: @bad[]"; + # } + + return @ns[ @ns ]; +} + + +constant @tests = + ( (0, 2, 1, 5, 3, 4), (0, 1, 2, 4, 5, 3) ), + ( (5, 0, 1, 2, 3, 4), (4, 5, 0, 1, 2, 3) ), + + # ( (5, 0, 1, 2, 3, 9), (9, 5, 0, 1, 2, Int) ), # Should warn. No time this week to implement testing of warnings. +; +use Test; plan +@tests; +for @tests -> ( @in, @expected ) { + is-deeply task2(Array[Int].new(@in)), @expected; +} -- cgit