exercism/c/queen-attack/queen_attack.c

116 lines
2.4 KiB
C

#include "queen_attack.h"
int same_position(position_t queen_1, position_t queen_2) {
if (queen_1.row == queen_2.row && queen_1.column == queen_2.column) {
return 1;
}
return 0;
}
int valid_position(position_t queen_1, position_t queen_2) {
// Queens cannot occupy the same position
if (same_position(queen_1, queen_2) ||
// Make sure both queens are actually on the board
(queen_1.row > 7 || queen_1.column > 7 || queen_2.row > 7 ||
queen_2.column > 7)) {
return 0;
}
return 1;
}
attack_status_t first_diagonal(position_t queen_1, position_t queen_2) {
position_t pos = queen_1;
while (pos.column <= 7) {
if (pos.row == 0)
break;
pos.row -= 1;
pos.column += 1;
if (same_position(pos, queen_2)) {
return CAN_ATTACK;
}
}
return CAN_NOT_ATTACK;
}
attack_status_t second_diagonal(position_t queen_1, position_t queen_2) {
position_t pos = queen_1;
while (pos.row <= 7) {
pos.row += 1;
pos.column -= 1;
if (same_position(pos, queen_2)) {
return CAN_ATTACK;
}
}
return CAN_NOT_ATTACK;
}
attack_status_t third_diagonal(position_t queen_1, position_t queen_2) {
position_t pos = queen_1;
for (int i = 0; i <= 7; i++) {
if (pos.row == 0 || pos.column == 0)
break;
pos.row -= 1;
pos.column -= 1;
if (same_position(pos, queen_2)) {
return CAN_ATTACK;
}
}
return CAN_NOT_ATTACK;
}
attack_status_t fourth_diagonal(position_t queen_1, position_t queen_2) {
position_t pos = queen_1;
for (int i = 0; i <= 7; i++) {
if (pos.row == 0 || pos.column == 0)
break;
pos.row -= 1;
pos.column -= 1;
if (same_position(pos, queen_2)) {
return CAN_ATTACK;
}
}
return CAN_NOT_ATTACK;
}
attack_status_t can_attack(position_t queen_1, position_t queen_2) {
// Check both positions are valid
if (!valid_position(queen_1, queen_2)) {
return INVALID_POSITION;
}
// Attack - Queens occupy the same row or column
if (queen_1.row == queen_2.row || queen_1.column == queen_2.column) {
return CAN_ATTACK;
}
attack_status_t status = CAN_NOT_ATTACK;
if (first_diagonal(queen_1, queen_2) == CAN_ATTACK ||
second_diagonal(queen_1, queen_2) == CAN_ATTACK ||
third_diagonal(queen_1, queen_2) == CAN_ATTACK ||
fourth_diagonal(queen_1, queen_2) == CAN_ATTACK) {
status = CAN_ATTACK;
}
return status;
}