简体   繁体   中英

Finding the Coordinates (2D Array) of Lowest Value

I feel like I'm missing something terribly obvious, but I cannot seem to find the array pair with the lowest value.

I have an int[,] worldMapXY where a 2D map is stored, say worldMapXY[0,0] through worldMapXY[120,120] . All values of map's array are 1 (wall\\invalid) or 0 (path/valid).

I'm writing a method that will find coordinates in one of the eight cardinal directions to create a spawn point. So I also have int[,] validSpotArr which has a subset of bounds of the map closest to the direction I'm setting the spawn. The values for wall/invalid locations are set to 9999 , the values for path/valid locations are set to (x + y) . This is all specific to the bottom left corner, nearest to [0,0] , hence "BL" or "Bottom Left"

        case "BL":

        for (int x = (int)border + 1; x < worldX + (int)border / 4; x++)
        {
            for (int y = (int)border + 1; y < worldY + (int)border / 4; y++) 
            {
                if (worldMapXY[x,y] = 0)
                {
                    validSpotArr[x,y] = x + y;
                }

                else
                {
                    validSpotArr[x,y] = 9999;
                }
            }
        }

What I can't quite wrap my head around is how to determine the coordinates/index of validSpotArr with the lowest value in such a way that I could pass those as separate x and y coordinates to another function (to set the spawn point). I suspect there's a lambda operator that may help, but I literally don't understand lambdas. Clearly that needs to be my next point of study.

Eg - if validSpotArr[23, 45] = 68 , and 68 is the lowest value, how do I set x=23 and y=45?

Edit: I tried messing around with something like this, but it isn't right:

    Array.IndexOf(validSpotArr, validSpotArr.Min());

While not precisely an answer to your question, in a strictly given situation I'd probably go for finding those from within the cycles, ie

int minValidSpot = int.MaxValue, minX, minY;
for (int x = (int)border + 1; x < worldX + int(border) / 4; x++)
    {
        for (int y = (int)border + 1; y < worldY + int(border) / 4; y++) 
        {
            if (worldMapXY[x,y] = 0)
            {
                validSpotArr[x,y] = x + y;
            }
            else
            {
                validSpotArr[x,y] = 9999;
            }
            if ( minValidSpot > validSpotArr[x,y] )
            {
                minValidSpot = validSpotArr[x,y];
                minX = x;
                minY = y;
            }
        }
    }

Other than that, if looking for some kind of more universal solution, I'd probably just flatten that array, the maths for index conversion (nD<=>1D) are pretty simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM