How can I get the last position in this jagged array?
I have a class like this that im using as the point in the array:
class Point
{
public int x;
public int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
and then im trying to get the value that is closest to the end with this:
public void Position()
{
for (int x = 0; x < arr.Length; x++)
{
for (int y = 0; y < arr[x].Length; y++)
{
if (arr[x][y] == 3)
Pos.x = x;
Pos.y =开发者_Python百科 y;
if (arr[x][y] == 1)
Pos.x = x;
Pos.y = y;
if (arr[x][y] == 2)
Pos.x = x;
Pos.y = y;
}
}
Console.Write("Last Position: {0}, {1}",LastPos.x, LastPos.y);
}
and i have this for the point:
public Point Pos = new Point(0, 0);
Its a jagged array filled with all zeros except for a few points. Looks like this:
0 0 0 3 0 0 0 0
0 0 1 0 0 0 0
0 0 0 2 0 0 0 0
0 0 0 0 0
0 0 0 0 0 0 0
Where 2 is the closest to the end in this example. with a position of 2,3 which i want Pos.x and Pos.y to be. It keeps giving me 0,30.
It looks like you are missing some curly braces.
if (arr[x][y] == 3)
{
Pos.x = x;
Pos.y = y;
}
if (arr[x][y] == 1)
{
Pos.x = x;
Pos.y = y;
}
if (arr[x][y] == 2)
{
Pos.x = x;
Pos.y = y;
}
In C# the indentation is not significant so your code is being interpreted as:
if (arr[x][y] == 3)
{
Pos.x = x;
}
Pos.y = y;
if (arr[x][y] == 1)
{
Pos.x = x;
}
Pos.y = y;
if (arr[x][y] == 2)
{
Pos.x = x;
}
Pos.y = y;
You could also simplify your code considerably:
if (arr[x][y] != 0)
{
Pos.x = x;
Pos.y = y;
}
Another problem is that you are setting Pos
but printing the value of LastPos
.
If you need better performance, note that it would be faster to start searching backwards from the end and break when you hit the first non-zero element instead of searching from the start and remembering the last non-zero element you've seen. This could terminate after checking just a few elements in many cases - in the best case only one element needs to be checked. So depending on the size of your data it could be hundreds of times faster to do it this way.
I'm not sure exactly where your variables are coming from, but it looks like you are setting the x/y in the Pos
variable and reading them from the LastPos
variable.
Maybe not the best answer, but here is something done with LINQ.
int[][] array = new int[][]
{
new int[] {0, 0, 0, 3, 0, 0, 0, 0},
new int[] {0, 0, 1, 0, 0, 0, 0},
new int[] {0, 0, 0, 2, 0, 0, 0, 0 },
new int[] {0, 0, 0, 0, 0 },
new int[] {0, 0, 0, 0, 0, 0, 0 }
};
var query = (from row in array.Select((r, idx) => new { r, idx })
where row.r.Any(item => item != 0)
select new
{
Row = row.idx,
Column = (from item in row.r.Select((i, idx) => new { i, idx })
where item.i != 0
select item.idx).Last()
}).Last();
Console.WriteLine("{0}\t{1}", query.Row, query.Column);
精彩评论