perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 381 - Task 1: Same Row Column

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-381/#TASK1
 3 #
 4 # Task 1: Same Row Column
 5 # =======================
 6 #
 7 # You are given a n x n matrix containing integers from 1 to n.
 8 #
 9 # Write a script to find if every row and every column contains all the
10 # integers from 1 to n.
11 #
12 ## Example 1
13 ##
14 ## Input: @matrix = ([1, 2, 3, 4],
15 ##                   [2, 3, 4, 1],
16 ##                   [3, 4, 1, 2],
17 ##                   [4, 1, 2, 3],)
18 ## Output: true
19 #
20 ## Example 2
21 ##
22 ## Input: @matrix = ([1])
23 ## Output: true
24 #
25 ## Example 3
26 ##
27 ## Input: @matrix = ([1, 2, 5],
28 ##                   [5, 1, 2],
29 ##                   [2, 5, 1],)
30 ## Output: false
31 ##
32 ## Elements are out of range 1..3.
33 #
34 ## Example 4
35 ##
36 ## Input: @matrix = ([1, 2, 3],
37 ##                   [1, 2, 3],
38 ##                   [1, 2, 3],)
39 ## Output: false
40 #
41 ## Example 5
42 ##
43 ## Input: @matrix = ([1, 2, 3],
44 ##                   [3, 1, 2],
45 ##                   [3, 2, 1],)
46 ## Output: false
47 #
48 ############################################################
49 ##
50 ## discussion
51 ##
52 ############################################################
53 #
54 # We just need to check whether each row and column contains
55 # all the numbers from 1..n. So we just do that, returning
56 # false in case any row or column doesn't fulfil this simple
57 # requirement.
58 
59 use v5.36;
60 
61 same_row_column([1, 2, 3, 4], [2, 3, 4, 1],
62                 [3, 4, 1, 2], [4, 1, 2, 3]);
63 same_row_column([1]);
64 same_row_column([1, 2, 5], [5, 1, 2], [2, 5, 1]);
65 same_row_column([1, 2, 3], [1, 2, 3], [1, 2, 3]);
66 same_row_column([1, 2, 3], [3, 1, 2], [3, 2, 1]);
67 
68 sub same_row_column(@matrix) {
69     say "Input: (";
70     foreach my $line (@matrix) {
71         say "[" . join(", ", @$line) . "],";
72     }
73     say ")";
74     my $n = scalar(@matrix);
75     foreach my $line (@matrix) {
76         return say "Output: false" unless is_this_ok(@$line);
77     }
78     foreach my $column (0..$n-1) {
79         my @tmp = ();
80         foreach my $line (@matrix) {
81             push @tmp, $line->[$column];
82         }
83         return say "Output: false" unless is_this_ok(@tmp);
84     }
85     say "Output: true";
86 }
87 
88 sub is_this_ok(@array) {
89     my $n = scalar(@array);
90     my $seen = {};
91     foreach my $elem (@array) {
92         $seen->{$elem} = 1;
93     }
94     foreach my $i (1..$n) {
95         return 0 unless $seen->{$i};
96     }
97     return 1;
98 }