For Programmers: Free Programming Magazines  


Home > Archive > PERL Miscellaneous > March 2005 > Re: sorting matrixes









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: sorting matrixes
Xah Lee

2005-03-28, 3:57 am

Here's the solution to previous post.

-------------------------------
perl code:

sub sort_matrix($$) {
my $ref_matrix =3D $_[0];
my @indexMatrix =3D @{$_[1]};

my @indexes =3D map {$_->[0]} @indexMatrix;
my @operators =3D map {$_->[1] ? ' cmp ' : ' <=3D> '} @indexMatrix;
my @directions =3D map {$_->[2]} @indexMatrix;

my $body_code =3D '';
my @body_array;
for (my $i =3D 0; $i <=3D $#indexes; $i++) {
if ($directions[$i]) {
push(@body_array, "(\$a->[$i]" . $operators[$i] .
"\$b->[$i])");
} else {
push(@body_array, "(\$b->[$i]" . $operators[$i] .
"\$a->[$i])");
};
};
$body_code =3D join( ' or ', @body_array);

my $array_code =3D '(map { [' . join(q(, ), map {"\$_->[$_]"}
@indexes) . ', $_]} @$ref_matrix)';

my $code =3D "map {\$_->[-1]} (sort { $body_code} $array_code)";
my @result =3D eval $code;
return [@result];
};

------------------------------------------
Python code

# python v 2.4

def sort_matrix(matrix, directives):
result=3Dmatrix
for dir in directives:
if dir[1]:
if dir[2]:
result.sort(lambda x,y: cmp( str(x[dir[0]]),
str(y[dir[0]])) )
else:
result.sort(lambda x,y: cmp( str(x[dir[0]]),
str(y[dir[0]])), None, True)
else:
if dir[2]:
result.sort(lambda x,y: cmp(float(x[dir[0]]),
float(y[dir[0]])) )
else:
result.sort(lambda x,y: cmp(float(x[dir[0]]),
float(y[dir[0]])), None, True )
return result

m =3D [
[3, 99, 'a'],
[2, 77, 'a'],
[1, 77, 'a']
]

print sort_matrix(m,[
[2,True,True],
[1,False,True]
])

The Python code has not been tested much.

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

Xah
xah@xahlee.org
=E2=88=91 http://xahlee.org/PageTwo_dir/more.html

=E2=98=84

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com