perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 324 - Task 1: 2D Array

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-324/#TASK1
 3 #
 4 # Task 1: 2D Array
 5 # ================
 6 #
 7 # You are given an array of integers and two integers $r amd $c.
 8 #
 9 # Write a script to create two dimension array having $r rows and $c columns
10 # using the given array.
11 #
12 ## Example 1
13 ##
14 ## Input: @ints = (1, 2, 3, 4), $r = 2, $c = 2
15 ## Output: ([1, 2], [3, 4])
16 #
17 #
18 ## Example 2
19 ##
20 ## Input: @ints = (1, 2, 3), $r = 1, $c = 3
21 ## Output: ([1, 2, 3])
22 #
23 #
24 ## Example 3
25 ##
26 ## Input: @ints = (1, 2, 3, 4), $r = 4, $c = 1
27 ## Output: ([1], [2], [3], [4])
28 #
29 ############################################################
30 ##
31 ## discussion
32 ##
33 ############################################################
34 #
35 # We just loop over the amount of rows and over the amount
36 # of columns, constructing the rows by creating the elements
37 # for it, and then in the end we have our result.
38 # If there are not enough elements in the input array, we return
39 # right away. If there are more elements in the array than are
40 # required, we just skip the remaining elements in the input
41 # array.
42 
43 use v5.36;
44 
45 twod_array( [1, 2, 3, 4], 2, 2 );
46 twod_array( [1, 2, 3], 1, 3 );
47 twod_array( [1, 2, 3, 4], 4, 1 );
48 twod_array( [1, 2, 3], 2, 2 );
49 twod_array( [1, 2, 3, 4, 5], 2, 2 );
50 
51 sub twod_array( $ints, $r, $c ) {
52     say "Input: [" . join(", ", @$ints) . "], $r, $c";
53     my @result = ();
54     if(scalar(@$ints) < $r * $c) {
55         return say "Not enough elements in array!";
56     }
57     foreach my $i (0..$r-1) {
58         my @tmp = ();
59         foreach my $j (0..$c-1) {
60             push @tmp, shift @$ints;
61         }
62         push @result, [ @tmp ];
63     }
64 
65     print "Output: [";
66     foreach my $elem (@result) {
67         print "[" . join(", ", @$elem) . "], ";
68     }
69     say "^H^H]";
70 }
71