perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 308 - Task 1: Count Common

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-308/#TASK1
 3 #
 4 # Task 1: Count Common
 5 # ====================
 6 #
 7 # You are given two array of strings, @str1 and @str2.
 8 #
 9 # Write a script to return the count of common strings in both arrays.
10 #
11 ## Example 1
12 ##
13 ## Input: @str1 = ("perl", "weekly", "challenge")
14 ##        @str2 = ("raku", "weekly", "challenge")
15 ## Output: 2
16 #
17 ## Example 2
18 ##
19 ## Input: @str1 = ("perl", "raku", "python")
20 ##        @str2 = ("python", "java")
21 ## Output: 1
22 #
23 ## Example 3
24 ##
25 ## Input: @str1 = ("guest", "contribution")
26 ##        @str2 = ("fun", "weekly", "challenge")
27 ## Output: 0
28 #
29 ############################################################
30 ##
31 ## discussion
32 ##
33 ############################################################
34 #
35 # Let's make sure that both arrays don't have duplicate entries. Then
36 # we can count all occurrences for all elements, which is either 1 or 2.
37 # In the latter case, we can add 1 to our result.
38 
39 use v5.36;
40 use List::Util qw(uniq);
41 
42 count_common( ["perl", "weekly", "challenge"], ["raku", "weekly", "challenge"]);
43 count_common( ["perl", "raku", "python"], ["python", "java"] );
44 count_common( ["guest", "contribution"], ["fun", "weekly", "challenge"] );
45 
46 sub count_common {
47    my ($str1, $str2) = @_;
48    print "Input: (" . join(", ", @$str1) . "), (" . join(", ", @$str2) . ")\n";
49    my @str1 = uniq(@$str1);
50    my @str2 = uniq(@$str2);
51    my $tmp;
52    my $result = 0;
53    foreach my $elem ( (@str1, @str2) ) {
54       $tmp->{$elem}++;
55       if($tmp->{$elem} > 1) {
56          $result++;
57       }
58    }
59    print "Output: $result\n";
60 }