RabbitFarm
2023-10-23
Same Consistent Strings
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1
You are given two arrays of strings. Write a script to find out if the word created by concatenating the array elements is the same.
Solution
use v5.36;
use boolean;
sub same_string{
my($a1, $a2) = @_;
return boolean(join(q//, @{$a1}) eq join(q//, @{$a2}));
}
MAIN:{
say same_string [qw/ab c/], [qw/a bc/];
say same_string [qw/ab c/], [qw/ac b/];
say same_string [qw/ab cd e/], [qw/abcde/];
}
Sample Run
$ perl perl/ch-1.pl
1
0
1
Notes
I really wracked my brain to try and come up with a simpler solution and I couldn't!
Part 2
You are given an array of strings and allowed string having distinct characters. A string is consistent if all characters in the string appear in the string allowed. Write a script to return the number of consistent strings in the given array.
Solution
use v5.36;
sub is_consistent{
my($s, $allowed) = @_;
$s =~ s/[$allowed]//g;
return $s eq q//;
}
sub consistent_strings{
my($strings, $allowed) = @_;
my @consistent = grep { is_consistent $_, $allowed } @{$strings};
return 0 + @consistent;
}
MAIN:{
say consistent_strings [qw/ad bd aaab baa badab/], q/ab/;
say consistent_strings [qw/a b c ab ac bc abc/], q/abc/;
say consistent_strings [qw/cc acd b ba bac bad ac d/], q/cad/;
}
Sample Run
$ perl perl/ch-2.pl
2
7
4
Notes
To check if a string is consistent using the given definition, all the allowed
characters are removed from the given string. If the result is the empty string then we
know the string meets the requirements. Here this is broken out to the is_consistent
function. That in turn is called from within a grep
which checks the entire list of
strings.
References
posted at: 00:24 by: Adam Russell | path: /perl | permanent link to this entry