[perl-python] sorting matrixes

Xah Lee xah at xahlee.org
Tue Mar 22 12:02:51 EST 2005


Today we'll write a program that can sort a matrix in all possible
ways.

Here's the Perl documentation. I'll post a Perl and Python version in 2
days.

-----------

sort_matrix( $matrix, [[$n1, $stringQ, $directionQ], [$n2, $stringQ,
$directionQ], ...]) sorts a matrix by $n1 th column then $n2 th...and
so on.

$matrix must be a reference to references of arrays, having the form
[[$e1, $e2,...], [...], ...].  $stringQ is a boolean indicating
whether to treat corresponding columns as a strings instead of as
number in the sorting process. True means string. $directionQ is a
boolean indicating ascending sort or not for the correpsonding
column. In the column spec $n1 $n2 ..., index counting starts at 0.

 Example:

 my $ref_matrix =
 [
   [3, 99, 'a'],
   [2, 77, 'a'],
   [1, 77, 'a']
 ];

sort_matrix( $ref_matrix,  [ [2,1,1], [1,0,1] ]);
# this means sort by third column, regarding it as strings,
# and in ascending order. If tie, sort by second column,
# regarding it as number, in ascending order.

# returns [[2,77,'a'],[1,77,'a'],[3,99,'a']];

------------------

Note: in the above, ignore the "must be a reference to references of
arrays". That's technical point, because Perl the language do nested
lists thru workaround of "references".

http://xahlee.org/perl-python/sort_matrix.html




More information about the Python-list mailing list