How do to: For loop in reverse order

366 views
Skip to first unread message

Andy C

unread,
May 5, 2016, 3:36:03 AM5/5/16
to AIMMS - The Modeling System
I would like to do a for loop over a set in *reverse* order.  In other words it loops over the last element, then the 2nd to last element etc.

Is this possible?

Thanks
AndyC

Dirk

unread,
May 5, 2016, 8:08:48 AM5/5/16
to AIMMS - The Modeling System
there are many ways to do what you want, but I would use a while or repeat loop instead of a for loop.  (Maybe it's just me, but I've always assumed that in a for statement the order can be whatever AIMMS wants.)
 
If you want a set with the elements reversed, just create a subset and use -Ord(index) in the order by attribute.  See Ref manual for more information.

Here are examples of the above

MySet := data { Q , Y, A , Z , F } ;
pCard := Card(MySet) ;
!----------------------------------
! Addressing elements in reverse order
!----------------------------------
s := "";
while (LoopCount <= pCard) do
eMySet := Element(MySet , pCard - Loopcount + 1 ) ; !gets elements in reverse order
! do whaterver you want using eMySet
s += FormatString("%e,", eMySet);
endwhile;
DialogMessage(s);
!----------------------------------
! or using a (reverse) sorted set
!----------------------------------
s := "";
MySortedSet := sort(iMySet, -ord(iMyset) ); 
while (LoopCount <= pCard) do
eMySet := Element(MySortedSet , Loopcount  ) ; !gets elements in reverse order
! do whaterver you want using eMySet
s += FormatString("%e,", eMySet);
endwhile;
DialogMessage(s);

Reply all
Reply to author
Forward
0 new messages