examples/sorting.mod
author Alpar Juttner <alpar@cs.elte.hu>
Sun, 05 Dec 2010 17:35:23 +0100
changeset 2 4c8956a7bdf4
permissions -rw-r--r--
Set up CMAKE build environment
     1 /* sorting.mod - how to sort arrays in MathProg */
     2 
     3 /* Written in GNU MathProg by Andrew Makhorin <mao@gnu.org> */
     4 
     5 #  Sometimes it is necessary to print parameters or variables in the
     6 #  order of ascending or descending their values. Suppose, for example,
     7 #  that we have the following subscripted parameter:
     8 
     9 set I := 1..12;
    10 
    11 param a{i in I} := Uniform(2, 7);
    12 
    13 #  If we print all its members:
    14 
    15 printf{i in I} "a[%d] = %g\n", i, a[i];
    16 
    17 #  the output may look like follows:
    18 #
    19 #  a[1]  = 2.64156
    20 #  a[2]  = 2.04798
    21 #  a[3]  = 2.14843
    22 #  a[4]  = 4.76896
    23 #  a[5]  = 6.09132
    24 #  a[6]  = 3.27780
    25 #  a[7]  = 4.06113
    26 #  a[8]  = 4.05898
    27 #  a[9]  = 6.63120
    28 #  a[10] = 6.50318
    29 #  a[11] = 3.46065
    30 #  a[12] = 4.69845
    31 #
    32 #  However, we would like the parameter members to appear in the order
    33 #  of ascending their values.
    34 #
    35 #  Introduce the following auxiliary parameter:
    36 
    37 param pos{i in I} :=
    38       1 + card({j in I: a[j] < a[i] or a[j] = a[i] and j < i});
    39 
    40 #  where pos[i] = k means that in the sorted list member a[i] would
    41 #  have k-th position, 1 <= k <= |I|. Then introduce another auxiliary
    42 #  parameter:
    43 
    44 param ind{k in 1..card(I)} := sum{i in I: pos[i] = k} i;
    45 
    46 #  where ind[k] = i iff pos[k] = i.
    47 #
    48 #  Now, the following statement:
    49 
    50 printf{k in 1..card(I)} "a[%d] = %g\n", ind[k], a[ind[k]];
    51 
    52 #  prints the parameter members in the desired order:
    53 #
    54 #  a[2]  = 2.04798
    55 #  a[3]  = 2.14843
    56 #  a[1]  = 2.64156
    57 #  a[6]  = 3.27780
    58 #  a[11] = 3.46065
    59 #  a[8]  = 4.05898
    60 #  a[7]  = 4.06113
    61 #  a[12] = 4.69845
    62 #  a[4]  = 4.76896
    63 #  a[5]  = 6.09132
    64 #  a[10] = 6.50318
    65 #  a[9]  = 6.63120
    66 
    67 end;