perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 385 - Task 1: Uncommon Words

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-385/#TASK1
 3 #
 4 # Task 1: Uncommon Words
 5 # ======================
 6 #
 7 # You are given two sentences.
 8 #
 9 # Write a script to return list of all uncommon words, order is not important.
10 #
11 ## Example 1
12 ##
13 ## Input: $sentence1 = "apple banana apple"
14 ##        $sentence2 = "banana orange"
15 ## Output: ("orange")
16 #
17 ## Example 2
18 ##
19 ## Input: $sentence1 = "cat dog"
20 ##        $sentence2 = "bird fish"
21 ## Output: ("cat", "dog", "bird", "fish")
22 #
23 ## Example 3
24 ##
25 ## Input: $sentence1 = "the quick brown fox"
26 ##        $sentence2 = "the quick"
27 ## Output: ("brown", "fox")
28 #
29 ## Example 4
30 ##
31 ## Input: $sentence1 = "hello"
32 ##        $sentence2 = "hello"
33 ## Output: ()
34 #
35 ## Example 5
36 ##
37 ## Input: $sentence1 = "blue blue red"
38 ##        $sentence2 = "red green green yellow"
39 ## Output: ("yellow")
40 #
41 ############################################################
42 ##
43 ## discussion
44 ##
45 ############################################################
46 #
47 # We count all words from both sentences. The uncommon ones are the
48 # ones that only appear once overall, so we put those into the
49 # result set.
50 
51 use v5.36;
52 
53 uncommon_words( "apple banana apple", "banana orange");
54 uncommon_words( "cat dog", "bird fish");
55 uncommon_words( "the quick brown fox", "the quick");
56 uncommon_words( "hello", "hello");
57 uncommon_words( "blue blue red", "red green green yellow");
58 
59 sub uncommon_words($sentence1, $sentence2) {
60     say "Input: \"$sentence1\", \"$sentence2\"";
61     my $found = {};
62     foreach my $word (split /\s+/, $sentence1) {
63         $found->{$word}++;
64     }
65     foreach my $word (split /\s+/, $sentence2) {
66         $found->{$word}++;
67     }
68     my @result = ();
69     foreach my $word (keys %$found) {
70         next unless $found->{$word} == 1;
71         push @result, $word;
72     }
73     say "Output: (" . join(", ", map {"\"$_\""} @result) . ")";
74 }