The weekly challenge 242 - Task 2: Flip Matrix

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-242/#TASK2
 3 #
 4 # Task 2: Flip Matrix
 5 # ===================
 6 #
 7 # You are given n x n binary matrix.
 8 #
 9 # Write a script to flip the given matrix as below.
10 #
11 # 1 1 0
12 # 0 1 1
13 # 0 0 1
14 #
15 # a) Reverse each row
16 #
17 # 0 1 1
18 # 1 1 0
19 # 1 0 0
20 #
21 # b) Invert each member
22 #
23 # 1 0 0
24 # 0 0 1
25 # 0 1 1
26 #
27 #
28 ## Example 1
29 ##
30 ## Input: @matrix = ([1, 1, 0], [1, 0, 1], [0, 0, 0])
31 ## Output: ([1, 0, 0], [0, 1, 0], [1, 1, 1])
32 #
33 ## Example 2
34 ##
35 ## Input: @matrix = ([1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0])
36 ## Output: ([1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0])
37 #
38 ############################################################
39 ##
40 ## discussion
41 ##
42 ############################################################
43 #
44 # Just reverse and invert. Nothing complicated.
45 
46 flip_matrix([1, 1, 0], [1, 0, 1], [0, 0, 0]);
47 flip_matrix([1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]);
48 
49 sub flip_matrix {
50    my @rows = @_;
51    my @result;
52    print "Input: (";
53    foreach my $row (@rows) {
54       print "[" . join(", ", @$row) . "],";
55    }
56    print ")\n";
57    foreach my $row (@rows) {
58       push @result, [ inverted( reverse @$row ) ];
59    }
60    print "Ouput: (";
61    foreach my $row (@result) {
62       print "[" . join(", ", @$row) . "],";
63    }
64    print ")\n";
65 }
66 
67 sub inverted {
68    my @array = @_;
69    my @result = ();
70    foreach my $elem (@array) {
71       push @result, $elem == 0 ? 1 : 0;
72    }
73    return @result;
74 }