comp.lang.ada
 help / color / mirror / Atom feed
From: Niklas Holsti <niklas.holsti@tidorum.invalid>
Subject: Re: Ada95 Help 2D arrays
Date: Fri, 20 Apr 2012 21:12:03 +0300
Date: 2012-04-20T21:12:03+03:00	[thread overview]
Message-ID: <9vdn7jFdmeU1@mid.individual.net> (raw)
In-Reply-To: <5774709.1285.1334943237337.JavaMail.geo-discussion-forums@vbbfk16>

On 12-04-20 20:33 , Will wrote:
> Here is my solution and no doubt it does work!

Looks pretty good to me. I have taken the liberty of cleaning up the 
formatting a bit, replacing the TABs with spaces. I have added some remarks.

> type Int_Array is array(Positive range<>) of Integer;
> type Int_Matrix is array(Positive range<>, Positive range<>) of Integer;
>
>
> function Best_Combined_Score(Grid : Int_Matrix) return Integer is

The problem statement said that the numbers in the Grid are positive 
integers. I would therefore use the type Natural instead of Integer for 
the function return type and the local variables.

>    Total       : integer := 0;
>    RowTotal    : integer := 0;
>    ColumnTotal : integer := 0;

The initializations of Total, RowTotal, and ColumnTotal are unnecessary: 
the variables are initialized below before being used.

>    Sum         : Integer := 0;
> begin	
> 	
>    for R in Grid'Range(1) loop

IMO it would be more balanced to call this (outermost) row index "Row", 
since it plays the same role as the "Column" index below, and use the 
identifier "R" in the inner loop over row indices.

>       RowTotal := 0;
>       for C in Grid'Range(2) loop
>          Rowtotal := Rowtotal +Grid(R,C);
>       end loop;
>
>       for Column in Grid'Range(2) loop
>          ColumnTotal := 0;
>          for Row in Grid'Range(1)loop
>             ColumnTotal := ColumnTotal + Grid(Row,Column);
>          end loop;
> 		                                                 		
>          Total := RowTotal + ColumnTotal - Grid(R, Column);
>
>          if Total > Sum then
>             Sum := Total;
>          end if;
>
>       end loop;
>    end loop;
> 		
>    return Sum;
> end Best_Combined_Score;

I think it works. But it is a cubic-complexity algorithm (loops nested 
three deep). A quadratic-complexity algorithm (loops nested two deep) 
would be more efficient for large grids. Of course, premature 
optimization is the root of much evil, but the quadratic algorithm is 
not much more difficult and demonstrates some nice aspects of local 
array variables in Ada.

-- 
Niklas Holsti
Tidorum Ltd
niklas holsti tidorum fi
       .      @       .



      reply	other threads:[~2012-04-20 18:12 UTC|newest]

Thread overview: 5+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2012-04-20 11:46 Ada95 Help 2D arrays Will
2012-04-20 16:27 ` Niklas Holsti
2012-04-20 16:55 ` Will
2012-04-20 17:33 ` Will
2012-04-20 18:12   ` Niklas Holsti [this message]
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox