Matrix chain multiplication: Difference between revisions
no edit summary
No edit summary |
No edit summary |
||
Line 29:
=={{header|Ada}}==
This example implements the pseudocode in the reference Wiki page. The pseudocode states that the index values for the array to multiply begin at 0 while the cost and order matrices employ index values beginning at 1. Ada supports this pseudocode directly because Ada allows the programmer to define the index range for any array type.
This Ada example is implemented using a simple package and a main procedure. The package specification is:
<lang ada>
package
type Vector is array (Natural range <>) of Integer;
procedure
end
</lang>
The implementation or body of the package is:
<lang ada>
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
package body
▲ type Result_Matrix is array(Natural range <>, Natural range <>) of Integer;
-- Chain_Multiplication --
procedure Chain_Multiplication (Dims : Vector) is
▲ ---------------------------------
▲ ---------------------------------
m : Result_Matrix (1 .. n, 1 .. n);
procedure
▲ n : Natural := Dims'Length - 1;
▲ S : Result_Matrix(0..n, 0..n);
▲ m : Result_Matrix(0..n, 0..n) := (Others =>(Others => 0));
begin
Put ("Array Dimension = (");
for I in Item'Range loop
Put (Item (I)'Image);
if I < Item'Last then
Put (",");
else
Put (")");
end if;
end loop;
Line 68:
end Print;
procedure Chain_Order (Item : Vector) is
J :
Cost : Natural;
Temp : Natural;
begin
for
end
M(I, J) := Integer'Last;▼
for I in 1 .. n
J
m
for K in I .. J
Temp := Item
end if;
end loop;
Line 91 ⟶ 95:
function Optimal_Parens return String is
function Construct
(S : Result_Matrix; I : Natural; J :
is
Us : Unbounded_String := Null_Unbounded_String;
Char_Order : Character;
begin
if I = J then
Char_Order := Character'Val
Append (Source
▲ New_Item => Char_Order);
return Us;
else
Append (Source
Append (Source =>
Append (Source
Append (Source =>
▲ New_Item => Construct(s, s(i,j) + 1, j));
▲ New_Item => ')');
return Us;
end if;
end Construct;
begin
return To_String (Construct (
end Optimal_Parens;
begin
Chain_Order (Dims);
Print (Dims);
Put_Line ("Cost = " & Integer'Image (m (
Put_Line ("Optimal Multiply = " & Optimal_Parens);
end Chain_Multiplication;
end
</lang>
The main procedure is:
<lang ada>
with
with Ada.Text_IO; use Ada.Text_IO;
procedure
V1 : Vector := (5, 6, 3, 1);
V2 : Vector := (1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2);
V3 : Vector := (1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10);
begin
New_Line;
New_Line;
end
</lang>
{{output}}
|