Skip to content

Instantly share code, notes, and snippets.

@sz332
Last active August 30, 2019 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sz332/4aba962ae58320a743eec94abcfd5169 to your computer and use it in GitHub Desktop.
Save sz332/4aba962ae58320a743eec94abcfd5169 to your computer and use it in GitHub Desktop.
public class Chessboard {
private final int maxX;
private final int maxY;
public Chessboard(int maxX, int maxY) {
this.maxX = maxX;
this.maxY = maxY;
}
public boolean isSafePosition(Position current, Figure... figures) {
for (Figure f : figures) {
for (Position reachablePosition : f.algorithm(this).getReachablePositions(f.location())) {
if (current.matches(reachablePosition)) {
return false;
}
}
}
return true;
}
public boolean isValidPosition(Position p) {
return p.isInside(0, 0, maxX - 1, maxY - 1);
}
}
public interface Figure {
Position location();
MovementAlgorithm algorithm(Chessboard board);
}
public class HorseFigure implements Figure {
private final Position location;
public HorseFigure(Position location) {
this.location = location;
}
@Override
public Position location() {
return location;
}
@Override
public MovementAlgorithm algorithm(Chessboard chessBoard) {
return new HorseMovementAlgorithm(chessBoard);
}
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class HorseMovementAlgorithm implements MovementAlgorithm {
private final Chessboard chessBoard;
public HorseMovementAlgorithm(Chessboard chessBoard) {
this.chessBoard = chessBoard;
}
@Override
public List<Position> getReachablePositions(Position current) {
return Arrays.asList(
current.delta(1, -2),
current.delta(-1, -2),
current.delta(1, 2),
current.delta(-1, 2),
current.delta(-2, 1),
current.delta(-2, -1),
current.delta(2, 1),
current.delta(2, -1))
.stream()
.filter(p -> chessBoard.isValidPosition(p))
.collect(Collectors.toList());
}
}
public interface MovementAlgorithm {
List<Position> getReachablePositions(Position current);
}
public class Position {
private final int x;
private final int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public boolean matches(Position p) {
return p.x == x && p.y == y;
}
public Position delta(int dx, int dy) {
return new Position(x + dx, x + dy);
}
public boolean isInside(int x0, int y0, int x1, int y1) {
return x >= x0 && x <= x1 && y >= y0 && y <= y1;
}
}
public class TestChessboard {
@Test
public void testChessboard1() {
Chessboard board = new Chessboard(8, 8);
HorseFigure figure = new HorseFigure(new Position(5, 5));
Assert.assertTrue(board.isSafePosition(new Position(0,0), figure));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment