Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

matrix w/ array 5

Status
Not open for further replies.

JohnLucania

Programmer
Oct 10, 2005
96
US
#! /usr/bin/perl
use strict;
use warnings;


my @ArrayNum = (1,2,3,4,5,6,7,8,9);

How do you display the numbers in matrix like below?

matrix 1)

1 2 3
4 5 6
7 8 9

matrix 2)
1 4 7
2 5 8
3 6 9

jl
 
This nearly fried my little brain... i hope you like it!

Code:
[b]#!/usr/bin/perl[/b]

my @arrayNum = (1..9);

# across
for ($x=0; $x<=$#arrayNum; $x++) {
  print $arrayNum[$x] . " ";
  print "\n" if ++$counter % (sqrt (scalar @arrayNum)) == 0;
}

print "\n";

# down
for ($i=1; $i<=sqrt (scalar @arrayNum); $i++) {
  for ($x=$i-1; $x<=$#arrayNum; $x+=sqrt (scalar @arrayNum)) {
    print $arrayNum[$x] . " ";
    print "\n" if ++$counter % (sqrt (scalar @arrayNum)) == 0;
  }
}


Kind Regards
Duncan
 
my suggestion is contrived since it's tailored to the exact data you posted but maybe could be adapted to a more universal solution:

Code:
my @ArrayNum = (1,2,3,4,5,6,7,8,9);
my $cols = 3;

horizontal(@ArrayNum);
vertical(@ArrayNum);

sub horizontal {
   my @temp = @_; 
   my @AofA = ();
   for (@temp) {
      push @AofA,[splice @temp,0,$cols];
   }
   print "@$_\n" for @AofA;
}

sub vertical {
   my @temp = @_; 
   my @AofA = ();
   for my $i (0..$cols-1) {
      $AofA[$i] = [@temp[$i,$i+$cols,$i+$cols*2]];
   }
   print "@$_\n" for @AofA;
}
 
that reminds me of doing matricies in assembly, why would a person subject themselves to such a thing in Perl? we have lists of lists for good reason

- Andrew
Text::Highlight - A language-neutral syntax highlighting module in Perl
also on SourceForge including demo
 
Do you really want to write this yourself?
There are a numer of modules for matrix processing.
Take a look at this.


Trojan.
 
Here's another way, but I agree with Trojan, there are probably modules that will take care of all this for you.
Code:
my @a=(1..9); my $root_a = sqrt(@a);

print "matrix 1:\n";
foreach (1..$root_a) {
    print join(' ', returnElements(\@a, ($_-1)*$root_a, 1)), "\n";
}

print "matrix 2:\n";
foreach (1..$root_a) {
    print join(' ', returnElements(\@a, $_-1, $root_a)), "\n";
}

sub returnElements {
    my ($a_ref, $curPos, $stepBy) = @_;
    my @temp;
    for (1..sqrt(@{$a_ref})) {
        push @temp, $a_ref->[$curPos];
        $curPos += $stepBy;
    }
    return @temp;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top