The weekly challenge 239 - Task 2: Consistent Strings

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-239/#TASK2
 3 #
 4 # Task 2: Consistent Strings
 5 # ==========================
 6 #
 7 # You are given an array of strings and allowed string having distinct
 8 # characters.
 9 #
10 ## A string is consistent if all characters in the string appear in the string
11 ## allowed.
12 #
13 # Write a script to return the number of consistent strings in the given array.
14 #
15 ## Example 1
16 ##
17 ## Input: @str = ("ad", "bd", "aaab", "baa", "badab")
18 ##        $allowed = "ab"
19 ## Output: 2
20 ##
21 ## Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.
22 #
23 ## Example 2
24 ##
25 ## Input: @str = ("a", "b", "c", "ab", "ac", "bc", "abc")
26 ##        $allowed = "abc"
27 ## Output: 7
28 #
29 ## Example 3
30 ##
31 ## Input: @str = ("cc", "acd", "b", "ba", "bac", "bad", "ac", "d")
32 ##        $allowed = "cad"
33 ## Output: 4
34 ##
35 ## Strings "cc", "acd", "ac", and "d" are consistent.
36 #
37 ############################################################
38 ##
39 ## discussion
40 ##
41 ############################################################
42 #
43 # Create a hash table that uses the characters of $allowed as
44 # the keys. Then for each string in the array, check all the
45 # characters. If one of those isn't in the hash table, the
46 # string is not consistent, so we don't count the string.
47 # Otherwise, count the string as consistent.
48 #
49 use strict;
50 use warnings;
51 
52 consistent_strings( ["ad", "bd", "aaab", "baa", "badab"], "ab");
53 consistent_strings( ["a", "b", "c", "ab", "ac", "bc", "abc"], "abc");
54 consistent_strings( ["cc", "acd", "b", "ba", "bac", "bad", "ac", "d"], "cad");
55 
56 sub consistent_strings {
57    my ($str, $allowed) = @_;
58    print "Input: \@str = (\"" . join("\", \"", @$str) . "\"), \$allowed = \"$allowed\"\n";
59    my %allowed_chars = map { $_ => 1, } split //, $allowed;
60    my $count = 0;
61    foreach my $string (@$str) {
62       my @chars = split //, $string;
63       my $consistent = 1;
64       foreach my $char (@chars) {
65          unless($allowed_chars{$char}) {
66             $consistent = 0;
67             last;
68          }
69       }
70       $count++ if $consistent;
71    }
72    print "Output: $count\n";
73 }
74