The weekly challenge 233 - Task 1: Similar Words

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-233/#TASK1
 3 #
 4 # Task 1: Similar Words
 5 # =====================
 6 #
 7 # You are given an array of words made up of alphabets only.
 8 #
 9 # Write a script to find the number of pairs of similar words. Two words are similar if they consist of the same characters.
10 #
11 ## Example 1
12 ##
13 ## Input: @words = ("aba", "aabb", "abcd", "bac", "aabc")
14 ## Output: 2
15 ##
16 ## Pair 1: similar words ("aba", "aabb")
17 ## Pair 2: similar words ("bac", "aabc")
18 #
19 ## Example 2
20 ##
21 ## Input: @words = ("aabb", "ab", "ba")
22 ## Output: 3
23 ##
24 ## Pair 1: similar words ("aabb", "ab")
25 ## Pair 2: similar words ("aabb", "ba")
26 ## Pair 3: similar words ("ab", "ba")
27 #
28 ## Example 3
29 ##
30 ## Input: @words = ("nba", "cba", "dba")
31 ## Output: 0
32 #
33 ############################################################
34 ##
35 ## discussion
36 ##
37 ############################################################
38 #
39 # For each possible combination of two words taken from the array,
40 # check if those two words are similar. Then return the sum of
41 # those pairs that are.
42 
43 use strict;
44 use warnings;
45 
46 similar_words("aba", "aabb", "abcd", "bac", "aabc");
47 similar_words("aabb", "ab", "ba");
48 similar_words("nba", "cba", "dba");
49 
50 sub similar_words {
51    my @words = @_;
52    print "Input: (" . join(", ", @words) . ")\n";
53    my $output = 0;
54    foreach my $i (0..$#words) {
55       foreach my $j ($i+1..$#words) {
56          $output++ if is_similar($words[$i], $words[$j]);
57       }
58    }
59    print "Output: $output\n";
60 }
61 
62 sub is_similar {
63    my ($word1, $word2) = @_;
64    my $result = 1;
65    my %w1_chars = map { $_ => 1, } split//, $word1;
66    my %w2_chars = map { $_ => 1, } split//, $word2;
67    foreach my $char (keys %w1_chars) {
68       return 0 unless $w2_chars{$char};
69    }
70    foreach my $char (keys %w2_chars) {
71       return 0 unless $w1_chars{$char};
72    }
73    return 1;
74 }