In: Computer Science
Prolog
On a 8x8 chessboard we use the predicate sq(X,Y) to identify a position (where X, Y are the corresponding square’s co-ordinates). A chess knight can move two squares in a left-right or front-back direction and then one square in a vertical fashion (https://en.wikipedia.org/wiki/Knight_(chess)).
We have defined the knightpath/1 predicate in the following incomplete Prolog program, which succeeds if invoked with a list of squares which are a valid position sequence for a chess knight.
Fill in the (ten) blanks to complete the program.
Then, show a Prolog query which succeeds by invoking knightpath/1 with a list of at least four successive legal knight moves.
knightpath([sq(X,Y)]) :- inboard(X), ___1___. knightpath([S1,S2|R]) :- jump(___2___), knightpath(___3___). jump(sq(X1,Y1),sq(X2,Y2)) :- ___4___, inboard(Y1), move(Dx,Dy), direction(Sx), ___5___, X2 is X1+Sx*Dx, ___6___. move(1,2). move(___7___). direction(1). ___8___. ___9___ (C) :- 0 < C, ___10___ . |
// CPP program to find number of possible moves of knight
#include <bits/stdc++.h>
#define n 4
#define m 4
using namespace std;
// To calculate possible moves
int findPossibleMoves(int mat[n][m], int p, int q)
{
// All possible moves of a knight
int X[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int Y[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
int count = 0;
// Check if each possible move is valid or not
for (int i = 0; i < 8; i++) {
// Position of knight after move
int x = p + X[i];
int y = q + Y[i];
// count valid moves
if (x >= 0 && y >= 0 && x < n && y < m
&& mat[x][y] == 0)
count++;
}
// Return number of possible moves
return count;
}
// Driver program to check findPossibleMoves()
int main()
{
int mat[n][m] = { { 1, 0, 1, 0 },
{ 0, 1, 1, 1 },
{ 1, 1, 0, 1 },
{ 0, 1, 1, 1 } };
int p = 2, q = 2;
cout << findPossibleMoves(mat, p, q);
return 0;
}