perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 375 - Task 1: Single Common Word

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-375/#TASK1
 3 #
 4 # Task 1: Single Common Word
 5 # ==========================
 6 #
 7 # You are given two array of strings.
 8 #
 9 # Write a script to return the number of strings that appear exactly once in
10 # each of the two given arrays. String comparison is case sensitive.
11 #
12 ## Example 1
13 ##
14 ## Input: @array1 = ("apple", "banana", "cherry")
15 ##        @array2 = ("banana", "cherry", "date")
16 ## Output: 2
17 #
18 ## Example 2
19 ##
20 ## Input: @array1 = ("a", "ab", "abc")
21 ##        @array2 = ("a", "a", "ab", "abc")
22 ## Output: 2
23 ##
24 ## "a" appears once in @array1 but appears twice in @array2, therefore, not counted.
25 #
26 ## Example 3
27 ##
28 ## Input: @array1 = ("orange", "lemon")
29 ##        @array2 = ("grape", "melon")
30 ## Output: 0
31 #
32 ## Example 4
33 ##
34 ## Input: @array1 = ("test", "test", "demo")
35 ##        @array2 = ("test", "demo", "demo")
36 ## Output: 0
37 #
38 ## Example 5
39 ##
40 ## Input: @array1 = ("Hello", "world")
41 ##        @array2 = ("hello", "world")
42 ## Output: 1
43 ##
44 ## String comparison is case sensitive.
45 #
46 ############################################################
47 ##
48 ## discussion
49 ##
50 ############################################################
51 #
52 # We count how often each word appears in the first array. Then we count
53 # all of the words in the second array that are exactly once in the
54 # first array. Then we count how many of those appeared exactly once.
55 
56 use v5.36;
57 
58 single_common_word(["apple", "banana", "cherry"],["banana", "cherry", "date"]);
59 single_common_word(["a", "ab", "abc"],["a", "a", "ab", "abc"]);
60 single_common_word(["orange", "lemon"],["grape", "melon"]);
61 single_common_word(["test", "test", "demo"],["test", "demo", "demo"]);
62 single_common_word(["Hello", "world"],["hello", "world"]);
63 
64 sub single_common_word($array1, $array2) {
65     say "Input: [" . join(", ", @$array1), "], [" . join(", ", @$array2) . "]";
66     my $candidates = {};
67     foreach my $word (@$array1) {
68         $candidates->{$word}++;
69     }
70     my $result = {};
71     foreach my $word (@$array2) {
72         next unless $candidates->{$word};
73         $result->{$word}++ if $candidates->{$word} == 1;
74     }
75     my $out = 0;
76     foreach my $res (keys %$result) {
77         $out++ if $result->{$res} == 1;
78     }
79     say "Output: $out";
80 }