Sorting in GAMS

Top  Previous  Next

GAMS code maybe employed to sort output as follows. (sorted.gms)

 

set i /a1*a6/;

alias(i,j);

parameter unsort(i)/a1 22,a2 33,a3 12,a4 15,a5 47,a6 22/;

set asord /1*1000/;

parameter gg(i);

gg(i)=sum(j$(unsort(j)>unsort(i)),1);

set orddat(asord,i);

orddat(asord,i)$(ord(asord)=(gg(i)+1))=yes;

file sorted;

put sorted;

loop(asord,

 if(sum(orddat(asord,i),1)=1,

  put 'In place ' asord.tl:0 ' with a value of '

   loop(orddat(asord,i),

     put unsort(i):0:0 ' is item ' @42 i.tl:0/))

     if(sum(orddat(asord,i),1)>1,

         put 'In place ' asord.tl:0 ' with a value of '

           smax(orddat(asord,i),unsort(i)):0:0 ' are items '

           loop(orddat(asord,i),put @42 i.tl:0 ' ' /);)        );

 

The result

 

In place 1 with a value of 47 is item    a5

In place 2 with a value of 33 is item    a2

In place 3 with a value of 22 are items  a1

                                         a6

In place 5 with a value of 15 is item    a4

In place 6 with a value of 12 is item    a3

 

This code counts the number of entries that have a larger value than the current one and then orders items in decreasing order using another dimension that gives their relative position.