N, Guruguhan (GEAE, Foreign National, EACOE) <> wrote:

:     In reply to my own posting, I have written a code
: like the one given below. 
:
:   @X = (1 .. 30);
: 
:   $n_el = scalar(@X);
:   $n_row = $n_el/3;      # 3 is the number of columns I want.
: 
:   for ($i=0; $i<$n_row; $i++) {
:      for ( $j=$i; $j <$n_el; $j+=$n_row) {
:      printf (  "%4d\t", $X[$j]);
:      }
:      printf ( "\n");
:   }
: When I execute, I get
:    1      11      21
:    2      12      22
:    3      13      23
:    4      14      24
:    5      15      25
:    6      16      26
:    7      17      27
:    8      18      28
:    9      19      29
:   10      20      30
: 
: Any comment on this welcome.

    First, you are not using 'my' for variable declaration,
which leads me to believe you aren't turning on warnings and
using strict. Let's rewrite your attempt with them.

use strict;
use warnings;

my @X = ( 1 .. 21 );

my $n_el = scalar(@X);
my $n_row = $n_el/3;      # 3 is the number of columns I want.

for ( my $i=0; $i<$n_row; $i++ ) {
    for ( my $j=$i; $j <$n_el; $j+=$n_row ) {
        printf (  "%4d\t", $X[$j]);
    }
    printf ( "\n");
}

__END__


    Second, this solution fails if the element count is
not evenly divisible by the column count. For the series
"1 .. 20" we get the following. Note the repeating 7.

my @X = 1 .. 20;

Result:

   1       7      14    
   2       8      15    
   3       9      16    
   4      10      17    
   5      11      18    
   6      12      19    
   7      13      20    

    This solution also fails if there is a non-numeric
value in @X. Not a constraint presented in the original
post. Note the extra 7 and 12 and the 0 in place of 'a'.

my @X = ( 1 .. 10, 'a', 11 .. 18 );

Argument "a" isn't numeric in printf at aa.pl line 14.
   1       7      12    
   2       8      13    
   3       9      14    
   4      10      15    
   5       0      16    
   6      11      17    
   7      12      18    

    Also note the trailing tab in each report. That's
pretty sloppy. Testing is a very big part of computer
programming. If you are doing this as anything more
than a hobby, you need to become better at testing
your algorithms.

HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
254 968-8328


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to