The weekly challenge 217 - Task 1: Sorted Matrix
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-217/#TASK1 3 # 4 # Task 1: Sorted Matrix 5 # ===================== 6 # 7 # You are given a n x n matrix where n >= 2. 8 # 9 # Write a script to find 3rd smallest element in the sorted matrix. 10 # 11 ## Example 1 12 ## 13 ## Input: @matrix = ([3, 1, 2], [5, 2, 4], [0, 1, 3]) 14 ## Output: 1 15 ## 16 ## The sorted list of the given matrix: 0, 1, 1, 2, 2, 3, 3, 4, 5. 17 ## The 3rd smallest of the sorted list is 1. 18 # 19 ## Example 2 20 ## 21 ## Input: @matrix = ([2, 1], [4, 5]) 22 ## Output: 4 23 ## 24 ## The sorted list of the given matrix: 1, 2, 4, 5. 25 ## The 3rd smallest of the sorted list is 4. 26 # 27 ## Example 3 28 ## 29 ## Input: @matrix = ([1, 0, 3], [0, 0, 0], [1, 2, 1]) 30 ## Output: 0 31 ## 32 ## The sorted list of the given matrix: 0, 0, 0, 0, 1, 1, 1, 2, 3. 33 ## The 3rd smallest of the sorted list is 0. 34 # 35 ############################################################ 36 ## 37 ## discussion 38 ## 39 ############################################################ 40 # 41 # This is straight forward. First, we create an array that 42 # consists of all elements from the matrix - @all in our case, 43 # which we fill while printing the input matrix. 44 # Then, we sort that. From the sorted array, we print the third 45 # element as the output. 46 47 use strict; 48 use warnings; 49 50 sorted_matrix([3, 1, 2], [5, 2, 4], [0, 1, 3]); 51 sorted_matrix([2, 1], [4, 5]); 52 sorted_matrix([1, 0, 3], [0, 0, 0], [1, 2, 1]); 53 54 sub sorted_matrix { 55 my @matrix = @_; 56 print "Input: ("; 57 my @all = (); 58 my $first = 1; 59 foreach my $part (@matrix) { 60 print ", " unless $first; 61 $first = 0; 62 print "[" . join(",",@$part) . "]"; 63 push @all, @$part; 64 } 65 print ")\n"; 66 my @sorted = sort {$a<=>$b} @all; 67 print "Output: $sorted[2]\n"; 68 } 69