Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

How to place values in an 2d array while maintaining that all of the values placed are within the array range and if not they are simply dismissed

I have the following code that positions a knight(chess piece) on a fictional chessboard or you can call it a 2d array of [8,8]. this chessboard is filled with zeros and where the knight is I put a (1)

 public Position PlaceKnight(int[,] chessboard)
    {
        Position p = new Position();
        Random rnd = new Random();
        chessboard[rnd.Next(0, 8), rnd.Next(0, 8)] = 1;
        for (int i = 0; i < chessboard.GetLength(0); i++)
        {
            for (int j = 0; j < chessboard.GetLength(1); j++)
            {
                if (chessboard[i, j] == 1)
                {
                    p.row = i;
                    p.culomn = j;
                    return p;
                }
            }
        }
        return p;
    }

Now I want to make a new function that checks the chessboard array see where the knight is and finally places the number (3) at every position the knight can move to. Now obviously the knight can move in 8 different position if the chessboard was clear and he was placed in the middle however the knight sometimes is at the corner of chessboard which mean he has limited movements! I was wondering What is the most efficient and fastest way to make that function that calculate the moves of the knight when given its position/index and the chessboard array as a parameter. I made this already but am pretty sure it doesn't work most of the times

void PossibleKnightMoves(int[,] chessboard, Position position)
    {


        for (int i = 0; i < chessboard.GetLength(0); i++)
        {
            for (int j = 0; j < chessboard.GetLength(1); j++)
            {
                if (i==position.row&&j==position.culomn)
                {
                    chessboard[i + 2, j - 1] = 3;
                    chessboard[i + 2, j +1] = 3;
                    chessboard[i - 2, j - 1] =3;
                    chessboard[i - 2, j +1] = 3;
                    chessboard[i - 1, j -2] = 3;
                    chessboard[i + 1, j -2] = 3;
                    chessboard[i - 1, j +2] = 3;
                    chessboard[i + 1, j +2] = 3;
                }
            }
        }

    }

Comments