How to sort a 2D array by column
monarch_dodra via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jun 7 13:35:30 PDT 2014
On Saturday, 7 June 2014 at 19:06:10 UTC, katuday wrote:
> the_table.sort; // I believe this sort uses all the columns
> inside the_row. What I want is use specific column(s)
Supposing you use the *function* "std.algorithm.sort", then that
is going to sort you rows according to the (default) predicate
"<".
In this case, "<" means lexicographical comparison for arrays.
EG: compares the first element, then the second, then the third,
until 2 are different.
I don't have your input, but here is an example program:
import std.stdio, std.algorithm, std.random;
//----
void main()
{
int[][] arr = new int[][](10, 10);
foreach(i; 0 .. 10)
foreach(j; 0 .. 10) {
arr[i][j] = rndGen().front % 5;
rndGen().popFront();
}
writefln("%(%s\n%)", arr.sort()); //Note the "()": Very
important.
}
//----
[0, 1, 0, 0, 0, 0, 2, 3, 1, 1]
[0, 4, 4, 1, 2, 3, 4, 2, 1, 0] </--
[0, 4, 4, 1, 3, 4, 0, 2, 3, 3] </--
[2, 0, 0, 4, 1, 3, 3, 4, 2, 4]
[2, 0, 4, 3, 3, 0, 2, 4, 2, 1]
[3, 1, 2, 1, 1, 4, 1, 4, 1, 2]
[3, 3, 2, 1, 0, 4, 0, 2, 3, 2]
[4, 0, 0, 4, 3, 0, 4, 3, 4, 2]
[4, 2, 1, 1, 1, 2, 0, 1, 2, 2]
[4, 4, 3, 2, 2, 1, 1, 0, 4, 2]
//----
As you can see here, this was ordered by looking up to 5 elements
deep.
If you need something more customize, you can do it by specifying
your own function. For example, according to each row's Euclidean
norm:
//----
bool compare(int[] lhs, int[] rhs) {
auto a = reduce!"a += b^2"(0, lhs);
auto b = reduce!"a += b^2"(0, rhs);
return a < b;
}
void main()
{
int[][] arr = new int[][](10, 4);
foreach(i; 0 .. 10)
foreach(j; 0 .. 4) {
arr[i][j] = rndGen().front % 9 - 4;
rndGen().popFront();
}
writefln("%(%2s\n%)", arr.sort!compare);
}
//----
[-2, -3, -1, 3]
[ 4, -2, -2, -2]
[-2, 0, 2, -4]
[ 3, -2, -4, 1]
[ 3, -2, 2, 3]
[-2, 3, 3, 0]
[ 1, 2, 0, -2]
[ 4, 2, -1, 0]
[ 2, 1, 1, 3]
[ 3, 3, 3, 4]
//----
In the above examples, I used numbers, but the language really
doesn't care, as long as your elements have strict total ordering
according to the predicate you have used.
More information about the Digitalmars-d-learn
mailing list