The weekly challenge 266 - Task 1: Uncommon Words

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-266/#TASK1
 3 #
 4 # Task 1: Uncommon Words
 5 # ======================
 6 #
 7 # You are given two sentences, $line1 and $line2.
 8 #
 9 # Write a script to find all uncommmon words in any order in the given two
10 # sentences. Return ('') if none found.
11 #
12 ### A word is uncommon if it appears exactly once in one of the sentences and
13 ### doesn’t appear in other sentence.
14 #
15 ## Example 1
16 ##
17 ## Input: $line1 = 'Mango is sweet'
18 ##        $line2 = 'Mango is sour'
19 ## Output: ('sweet', 'sour')
20 #
21 ## Example 2
22 ##
23 ## Input: $line1 = 'Mango Mango'
24 ##        $line2 = 'Orange'
25 ## Output: ('Orange')
26 #
27 ## Example 3
28 ##
29 ## Input: $line1 = 'Mango is Mango'
30 ##        $line2 = 'Orange is Orange'
31 ## Output: ('')
32 #
33 ############################################################
34 ##
35 ## discussion
36 ##
37 ############################################################
38 #
39 # The task is to find word that only appear once across two sentence.
40 # So we split the sentences into the single words and count each one.
41 # We can avoid creating two loops by concatenating the two sentences
42 # first. 
43 
44 use strict;
45 use warnings;
46 
47 uncommon_words('Mango is sweet', 'Mango is sour');
48 uncommon_words('Mango Mango', 'Orange');
49 uncommon_words('Mango is Mango', 'Orange is Orange');
50 
51 sub uncommon_words {
52    my ($line1, $line2) = @_;
53    print "Input: '$line1', '$line2'\n";
54    my $words = {};
55    my @output = ();
56    foreach my $word (split /\s+/, "$line1 $line2") {
57       $words->{$word}++
58    }
59    foreach my $word (keys %$words) {
60       push @output, $word if $words->{$word} == 1;
61    }
62    if(@output) {
63       print "Output: ('", join("', '", @output), "')\n";
64    } else {
65       print "Output: ('')\n";
66    }
67 }