The weekly challenge 293 - Task 1: Similar Dominos

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-293/#TASK1
 3 #
 4 # Task 1: Similar Dominos
 5 # =======================
 6 #
 7 # You are given a list of dominos, @dominos.
 8 #
 9 # Write a script to return the number of dominoes that are similar to any other
10 # domino.
11 #
12 ### $dominos[i] = [a, b] and $dominos[j] = [c, d] are same if either (a = c and
13 ### b = d) or (a = d and b = c).
14 #
15 ## Example 1
16 ##
17 ## Input: @dominos = ([1, 3], [3, 1], [2, 4], [6, 8])
18 ## Output: 2
19 ##
20 ## Similar Dominos: $dominos[0], $dominos[1]
21 #
22 ## Example 2
23 ##
24 ## Input: @dominos = ([1, 2], [2, 1], [1, 1], [1, 2], [2, 2])
25 ## Output: 3
26 ##
27 ## Similar Dominos: $dominos[0], $dominos[1], $dominos[3]
28 #
29 ############################################################
30 ##
31 ## discussion
32 ##
33 ############################################################
34 #
35 # First, we create a list of sorted dominos (so [3, 1] turns into
36 # [1, 3]). Then, we count each domino by using the first number as
37 # the first key and the second number as the second key in a
38 # nested hash. In the end, we sum up all hash elements with more
39 # than one occurence.
40 
41 use strict;
42 use warnings;
43 
44 similar_dominos([1, 3], [3, 1], [2, 4], [6, 8]);
45 similar_dominos([1, 2], [2, 1], [1, 1], [1, 2], [2, 2]);
46 
47 sub similar_dominos {
48    my @dominos = @_;
49    my @sorted_dominos = map { [ sort @$_ ] } @dominos;
50    print "Input: (" . join(", ", map { "[$_->[0], $_->[1]]" } @dominos ) . ")\n";
51    print "Sorted input: (" . join(", ", map { "[$_->[0], $_->[1]]" } @sorted_dominos ) . ")\n";
52    my $data;
53    foreach my $domino (@sorted_dominos) {
54       $data->{$domino->[0]}->{$domino->[1]}++;
55    }
56    my $count = 0;
57    foreach my $i (keys %$data) {
58       foreach my $j (keys %{$data->{$i}}) {
59          $count += $data->{$i}->{$j} if $data->{$i}->{$j} > 1;
60       }
61    }
62    print "Output: $count\n";
63 }
64