Page 1 of 1

Sort a rectangular array of values by values in 1 or 2 rows?

Posted: Wed Nov 04, 2015 11:19 am
by macro
I have a rectangular array of integers like this:

Code: Select all

2 2 2 3 3 1 1 0
2 1 3 1 2 3 4 0
and I'd like to sort it by the values in the first row, with ties broken by the values in the second row. Any ties that remain can be "broken" arbitrarily. I'm hoping to avoid implementing my own sort routine for this, but that seems nontrivial because RATS doesn't have any form of stack or linked list data type that can use during the sort. The only strategy I can think of is to cast the rectangular array into a matrix of reals, transpose it, use %sortcl on both columns or some combination of %index calls, then use those indexes on the the original rectangular. Is there a better way to do this?

Using the generic %sort function

Code: Select all

compute v1 = ||2,2,2,3,3,1,1,0|2,1,3,1,2,3,4,0||
display %sort(v1)
returns

Code: Select all

0 0 1 1 1 1 2 2
but I'm not sure how to interpret that output. It seems like it's sorting -v1- without respect to rows or columns, and then truncating the output to the number of columns in -v1-.

Re: Sort a rectangular array of values by values in 1 or 2 r

Posted: Wed Nov 04, 2015 11:48 am
by TomDoan
Wouldn't this work:

Code: Select all

dec rect[int] myint(2,8)
input myint
2 2 2 3 3 1 1 0
2 1 3 1 2 3 4 0
dec rect[real] mytrreal(%cols(myint),%rows(myint))
ewise mytrreal(i,j)=myint(j,i)
compute mytrreal=%sortcl(mytrreal,||1,2||)
ewise myint(i,j)=fix(mytrreal(j,i))

Re: Sort a rectangular array of values by values in 1 or 2 r

Posted: Thu Nov 05, 2015 4:20 pm
by macro
That's what I was looking for; thank you.