You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.5 KiB

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