P
peorro77
How can i use IComparer to sort a grid of rows and lines?
This is what i need:
Shuffle Arraylist
Field ROW Field LINE
5 2
5 3
4 2
6 2
6 3
3 2
6 3
7 4
7 3
7 5
This is what i expect:
Sorted Arraylist
Field ROW Field LINE
3 2
4 2
5 2
5 3
6 2
6 3
7 3
7 4
7 5
This is the code in which i'm working (this code only sort the row field, but how can i sort by row (as main) and line (as secondary)
public class MainClass {
System.Collections.ArrayList objs = new System.Collectios.ArrayList();
public MainClass() {
for(int row = 0; row < 8; row ++) {
for(int line = 0; line < 8; line ++) {
objs.Add(new MyClass(row,line);
}
}
objs = Shuffle(objs);
objs.Sort(new sortalgo);
}
}
public class MyClass
{
public row;
public line;
public MyClass(int row, int line) {
this.row=row;
this.line=line;
}
}
public class sortalgo : System.Collections.IComparer
{
public int Compare(object left, object right)
{
int row_left = ((MyClass)left).row;
int row_right = ((MyClassl)right).row;
if (row_left == row_right)
return 0;
if (row_left < row_right)
return -1;
return +1;
}
}
This is what i need:
Shuffle Arraylist
Field ROW Field LINE
5 2
5 3
4 2
6 2
6 3
3 2
6 3
7 4
7 3
7 5
This is what i expect:
Sorted Arraylist
Field ROW Field LINE
3 2
4 2
5 2
5 3
6 2
6 3
7 3
7 4
7 5
This is the code in which i'm working (this code only sort the row field, but how can i sort by row (as main) and line (as secondary)
public class MainClass {
System.Collections.ArrayList objs = new System.Collectios.ArrayList();
public MainClass() {
for(int row = 0; row < 8; row ++) {
for(int line = 0; line < 8; line ++) {
objs.Add(new MyClass(row,line);
}
}
objs = Shuffle(objs);
objs.Sort(new sortalgo);
}
}
public class MyClass
{
public row;
public line;
public MyClass(int row, int line) {
this.row=row;
this.line=line;
}
}
public class sortalgo : System.Collections.IComparer
{
public int Compare(object left, object right)
{
int row_left = ((MyClass)left).row;
int row_right = ((MyClassl)right).row;
if (row_left == row_right)
return 0;
if (row_left < row_right)
return -1;
return +1;
}
}