An interesting way of coding it
Послано
Egor 18 ноя 2016 02:11
There is an interesting way to code it.
For each piece we can have a function like this:
pair<string, int> get_king(int n, int x0, int y0)
{
int cnt = 0;
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++)
if (dx != 0 || dy != 0)
{
int x = x0 + dx;
int y = y0 + dy;
cnt += (x >= 1 && x <= n && y >= 1 && y <= n);
}
return { "King", cnt };
}
In the main code we just do the following loop:
for (auto get : { get_king, get_knight, get_bishop, get_rook, get_queen })
{
auto res = get(n, x, y);
cout << res.first << ": " << res.second << endl;
}
After that the function for queen look very easy:
pair<string, int> get_queen(int n, int x0, int y0)
{
int cnt = get_rook(n, x0, y0).second + get_bishop(n, x0, y0).second;
return { "Queen", cnt };
}
If you have any ideas on how to code it better, please write them here :)