The weekly challenge 220 - Task 1: Common Characters

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-220/#TASK1
 3 #
 4 # Task 1: Common Characters
 5 # =========================
 6 #
 7 # You are given a list of words.
 8 #
 9 # Write a script to return the list of common characters (sorted alphabeticall) found in every word of the given list.
10 #
11 ## Example 1
12 ##
13 ## Input: @words = ("Perl", "Rust", "Raku")
14 ## Output: ("r")
15 #
16 ## Example 2
17 ##
18 ## Input: @words = ("love", "live", "leave")
19 ## Output: ("e", "l", "v")
20 #
21 ############################################################
22 ##
23 ## discussion
24 ##
25 ############################################################
26 #
27 # We split the word in lowercase into its characters, keeping track
28 # of each character that is in the word (only count it once per word).
29 # Then we check which characters appeared as often as there are words.
30 
31 use strict;
32 use warnings;
33 
34 common_characters("Perl", "Rust", "Raku");
35 common_characters("love", "live", "leave");
36 
37 sub common_characters {
38    my @words = @_;
39    print "Input: (" . join(", ", @words) . ")\n";
40    my $words = scalar(@words);
41    my $data ={};
42    foreach my $word (@words) {
43       my $seen;
44       foreach my $char (split //,lc($word)) {
45          $data->{$char}++ unless $seen->{$char}++;
46       }
47    }
48    my $result;
49    foreach my $char (sort keys %$data) {
50       push @$result, $char if $data->{$char} == $words;
51    }
52    print "Output: (" . join(", ", @$result) . ")\n";
53 }
54