# Help optimizing my code for chess game

Hey im working on a chess clone and made some code to generate names for each tile in the board grid. In chess each coordinate of tiles are defined by a letter in width and a number in length. I have this code for generating letters for the tiles but as you can see its messy and could be optimized

``````                if (tiles.Count <= width)
{
piece.name = "a";
}
if (tiles.Count <= width * 2 && tiles.Count >= width + 1)
{
piece.name = "b";
}
if (tiles.Count <= width * 3 && tiles.Count >= width * 2 + 1)
{
piece.name = "c";
}
if (tiles.Count <= width * 4 && tiles.Count >= width * 3 + 1)
{
piece.name = "d";
}
if (tiles.Count <= width * 5 && tiles.Count >= width * 4 + 1)
{
piece.name = "e";
}
if (tiles.Count <= width * 6 && tiles.Count >= width * 5 + 1)
{
piece.name = "f";
}
if (tiles.Count <= width * 7 && tiles.Count >= width * 6 + 1)
{
piece.name = "g";
}
if (tiles.Count <= width * 8 && tiles.Count >= width * 7 + 1)
{
piece.name = "h";
}
``````

tiles is the list where i store all tiles. width is the width of the grid with and value of 8. piece is the gameobject that every tile is assigned to in the for-loop and when you access the piece object u access all of them in the grid.

Im going to do one for length aswell where you assign numbers and it works pretty much the same. How can i optimize this code and make it shorter than it is? Thanks

For the numbers (refactoring your code in the comment) I guess you could do:

``````int rest = tiles.Count % length;
if (rest == 0) rest = 8;
piece.name = piece.name + rest.ToString();
``````

For the letters you could do something like this:

``````char letter = 'a';
int count = tiles.Count;
while (count > length) {
count -= length;
letter++;
}
piece.name = letter.ToString();
``````

I’ve not tested this code, but that’s the cleanest idea I can think off.

EDIT: It looks like you can just increment a char instead of using an int and avoid using ascii codes and costs, I changed the code a bit.