SECTION 13.2 ITERATING OVER A SET: THE FOR STATEMENT 261
By writing a script that uses the printf command (A.16), we can create a much more
effective table:
ampl: commands steelT.tab1;
SALES bands coils
week 1 6000 100.0% 307 7.7%
week 2 6000 100.0% 2500 100.0%
week 3 1399 35.0% 3500 100.0%
week 4 1999 30.8% 4200 100.0%
The script to write this table can be as short as two printf commands:
printf "\n%s%14s%17s\n", "SALES", "bands", "coils";
printf {t in 1..T}: "week %d%9d%7.1f%%%9d%7.1f%%\n", t,
Sell["bands",t], 100*Sell["bands",t]/market["bands",t],
Sell["coils",t], 100*Sell["coils",t]/market["coils",t];
This approach is undesirably restrictive, however, because it assumes that there will
always be two products and that they will always be named coils and bands. In fact
the printf statement cannot write a table in which both the number of rows and the
number of columns depend on the data, because the number of entries in its format string
is always fixed.
A more general script for generating the table is shown in Figure 13-2. Each pass
through the ‘‘outer’’ loop over {1..T} generates one row of the table. Within each
pass, an ‘‘inner’’ loop over PROD generates the row’s product entries. There are more
printf statements than in the previous example, but they are shorter and simpler. We
use several statements to write the contents of each line; printf does not begin a new
line except where a newline (\n) appears in its format string.
Loops can be nested to any depth, and may be iterated over any set that can be repre-
sented by an AMPL set expression. There is one pass through the loop for every member
of the set, and if the set is ordered — any set of numbers like 1..T, or a set declared
ordered or circular — the order of the passes is determined by the ordering of the
set. If the set is unordered (like PROD) then AMPL chooses the order of the passes, but
________________________________________________________________________
____________________________________________________________________________________________________________________________________________________________________________________
printf "\nSALES";
printf {p in PROD}: "%14s ", p;
printf "\n";
for {t in 1..T} {
printf "week %d", t;
for {p in PROD} {
printf "%9d", Sell[p,t];
printf "%7.1f%%", 100 * Sell[p,t]/market[p,t];
}
printf "\n";
}
Figure 13-2: Generating a formatted sales table with nested loops (steelT.tab1).
____________________________________________________________________________________________________________________________________________________________________________________
________________________________________________________________________