aboutsummaryrefslogtreecommitdiff
path: root/challenge-004/james-smith/perl6
diff options
context:
space:
mode:
authorbagheera-sands <git@sandsscouts.org.uk>2019-04-15 14:45:35 +0100
committerbagheera-sands <git@sandsscouts.org.uk>2019-04-15 14:45:35 +0100
commit94cceaf1acf32d92490f115eb7e09c09795d165a (patch)
treebee11f78bb6380ca170b90eb48d8eb0a992f02e5 /challenge-004/james-smith/perl6
parent7d46beb6e5542ac60bdefbda413c30826c81d81b (diff)
downloadperlweeklychallenge-club-94cceaf1acf32d92490f115eb7e09c09795d165a.tar.gz
perlweeklychallenge-club-94cceaf1acf32d92490f115eb7e09c09795d165a.tar.bz2
perlweeklychallenge-club-94cceaf1acf32d92490f115eb7e09c09795d165a.zip
changes to solution for challenge 2 - a bit longer but non-destructive!
Diffstat (limited to 'challenge-004/james-smith/perl6')
-rw-r--r--challenge-004/james-smith/perl6/ch-2.p629
1 files changed, 15 insertions, 14 deletions
diff --git a/challenge-004/james-smith/perl6/ch-2.p6 b/challenge-004/james-smith/perl6/ch-2.p6
index 1b2ad01c7c..c780d7faaa 100644
--- a/challenge-004/james-smith/perl6/ch-2.p6
+++ b/challenge-004/james-smith/perl6/ch-2.p6
@@ -1,27 +1,28 @@
use strict;
-## Read in letters from command line... and store in %c...
+## Read in letters from command line... and store in %counts...
## We split each argument so words can be passed in rather
## than individual letters if required...
+## To avoid the additional non-letter characters we have to
+## use the :skip-empty flag...
my %counts;
-for @*ARGS -> $w {
- %counts{lc $_}++ for split '',$w, :skip-empty;
+for @*ARGS {
+ %counts{lc $_}++ for split '',$_, :skip-empty;
}
-for $*IN.lines() -> $word {
- my %copy = %counts.clone;
- say $word if checkword(lc($word),%copy);
-}
+## Re-write as a one-liner by using `for grep` rather than `for {if}`...
+
+say $_ for grep { checkword(lc $_) }, $*IN.lines();
-## Check the word to see if it can be made up from letters
-## use passing a hash by value to clone the counts so we
-## don't destroy it through each loop {the method is
-## destructive!}
+## Rewritten this to make it non destructive - we count up rather than
+## down needs another check to avoid comparing to undef...
+## So this is probably a nicer way of doing it....
-sub checkword($word,%copy_counts) {
- for (split '',$word, :skip-empty) -> $letter {
- return if --%copy_counts{$letter} < 0;
+sub checkword($word) {
+ my %tmp_counts;
+ for (split '',$word, :skip-empty) {
+ return unless %counts{$_} && %tmp_counts{$_}++ < %counts{$_};
}
return 1;
}