Mev
Mev

Reputation: 1625

How to Sort an array on descending order with minizinc

In minizinc there is an inbuild sort function to sort a 1d array which sorts the elements by their ascending order. How do I do the opposite? I could not find a function directly associated with it. Or given I can use the sort function can I traverse this from end to start?

array[TYPE] of int: input;

% gives ascending ordered array
array[TYPE] of int: sorted = sort(input); 

array[TYPE] of int: reverse_sorted = ???? 

Upvotes: 1

Views: 71

Answers (2)

Axel Kemper
Axel Kemper

Reputation: 11322

A sort() combined with reverse() achieves a descending sort:

array[1..5] of int: a = reverse(sort([7,29, 3, 1, 29]));

output [ show(a[i]) ++ " " | i in 1..5];

Your example:

%  compiles with MiniZinc 2.8.7
set of int: TYPE = 1..5;
array[TYPE] of int: input;

% gives ascending ordered array
array[TYPE] of int: sorted = sort(input); 

array[TYPE] of int: reverse_sorted = reverse(sorted); 

output [show(reverse_sorted[i]) ++ " " | i in TYPE];

Upvotes: 1

jitter
jitter

Reputation: 54615

I think this should work

array[TYPE] of int: reverse_sorted = [sorted[TYPE[length(TYPE) - i + 1]] | i in index_set(TYPE)];

Upvotes: 1

Related Questions