R – How to create a 2-dimentional matrix and feed information from arrays in Perl

arraysmatrixmultidimensional-arrayperl

I have four arrays @A1, @A2, @A3, @A4 each with same number of elements, say 6.
I want to create a 2 dimensional array which stores the values of two array elements
I want output corresponding to following format.
For example

Array1: A B C D E F
Array2: E F G H I J
Array3: Q W E R T Y
Array4: P O L I U G

Then the Matrix should be:

[0,0] = A E [0,1] = B F [0,2] = C G [0,3] = D H  [0,4] = E I  [0,5] = F J
[1,0] = Q P [1,1] = W O [1,2] = E L [1,3] = R I  [1,4] = T U  [1,5] = Y G

I will be doing the above for a lot number of arrays than just 4. So I will have to write some sort of loop.

Any suggestions on doing the same?

Best Solution

Hope this helps.

use strict;
use warnings;

my @A1 = qw'A B C D E F';
my @A2 = qw'E F G H I J';
my @A3 = qw'Q W E R T Y';
my @A4 = qw'P O L I U G';

my @matrix;
$matrix[0][4] = [ $A1[3], $A2[3] ];

# Use one of the following

for(
  my $i=0;
  $i<@A1 || $i<@A2 || $i<@A3 || $i<@A4;
  $i++
){
  $matrix[0][$i+1] = [ $A1[$i], $A2[$i] ];
  $matrix[1][$i+1] = [ $A3[$i], $A4[$i] ];
}

# OR

for(
  my $i=0;
  $i<@A1 || $i<@A2 || $i<@A3 || $i<@A4;
  $i++
){
  push @{ $matrix[0] }, [ $A1[$i], $A2[$i] ];
  push @{ $matrix[1] }, [ $A3[$i], $A4[$i] ];
}

# OR

{
  my $i = 1;
  for my $elem (@A1){
    push @{ $matrix[0][$i++] }, $elem;
  }
  $i = 1;
  for my $elem (@A2){
    push @{ $matrix[0][$i++] }, $elem;
  }
  $i = 1;
  for my $elem (@A3){
    push @{ $matrix[1][$i++] }, $elem;
  }
  $i = 1;
  for my $elem (@A4){
    push @{ $matrix[1][$i++] }, $elem;
  }
}
# notice how $i is out of scope here

To print it out you could use Data::Dumper or YAML

use 5.010;

use Data::Dumper;
$Data::Dumper::Terse = 1;
$Data::Dumper::Indent = 1;
say Dumper \@matrix;

use YAML;
say Dump   \@matrix;

use Data::Dump 'dump';
say dump \@matrix;

Data::Dumper

[
  [
    [
      'A',
      'E'
    ],
    [
      'B',
      'F'
    ],
    [
      'C',
      'G'
    ],
    [
      'D',
      'H'
    ],
    [
      'E',
      'I'
    ],
    [
      'F',
      'J'
    ]
  ],
  [
    [
      'Q',
      'P'
    ],
    [
      'W',
      'O'
    ],
    [
      'E',
      'L'
    ],
    [
      'R',
      'I'
    ],
    [
      'T',
      'U'
    ],
    [
      'Y',
      'G'
    ]
  ]
]

YAML

---
-
  -
    - A
    - E
  -
    - B
    - F
  -
    - C
    - G
  -
    - D
    - H
  -
    - E
    - I
  -
    - F
    - J
-
  -
    - Q
    - P
  -
    - W
    - O
  -
    - E
    - L
  -
    - R
    - I
  -
    - T
    - U
  -
    - Y
    - G

Data::Dump

[
  [
    ["A", "E"],
    ["B", "F"],
    ["C", "G"],
    ["D", "H"],
    ["E", "I"],
    ["F", "J"],
  ],
  [
    ["Q", "P"],
    ["W", "O"],
    ["E", "L"],
    ["R", "I"],
    ["T", "U"],
    ["Y", "G"],
  ],
]