Question Index

In chess, assuming that the columns are numbered A to H and the rows are numbered 1 to 8. Write a program to find all the positions to which a black elephant can move to without getting killed by the white horse. Assume that there is nothing else on the chess board apart from these two.
NOTE: The list returned should be first sorted by columns and then by rows, so A4 comes before B1 and C7 comes before D5 etc.,

Input (Black Elephant Position, White Horse Position) Output (Sorted List of Positions)
Elephant = A3, Horse = E4 [A1, A2, A4, A5, A6, A7, A8, B3, D3, E3, F3, H3]
Elephant = E3, Horse = A2 [A3, B3, D3, E1, E2, E4, E5, E6, E7, E8, F3, G3, H3]
Elephant = H3, Horse = F1 [A3, B3, C3, D3, F3, H1, H4, H5, H6, H7, H8]
Elephant = H3, Horse = H2 [A3, B3, C3, D3, E3, G3, H1, H4, H5, H6, H7, H8]

class FindBlackElephantPositionsWithWhiteHorse

{    public static void main(String s[])
        ChessPosition blackElephant = new ChessPosition('H', 3);
        ChessPosition whiteHorse = new ChessPosition('H', 2);
        System.out.println("The positions which the black elephant can move to with out getting killed : " + getPossiblePositions(blackElephant, whiteHorse));


public static List<ChessPosition> getPossiblePositions(ChessPosition blackElephant, ChessPosition whiteHorse) {
//Write code here to get the positions in which the elephant can move to with out getting killed by white horse
class ChessPosition {

char column;
int row;

public ChessPosition(char column, int row) {
this.column = column;
this.row = row;

public String toString() {
return column + "" + row;



Topic: Java ArrayList

Read this topic
Take test on this topic

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App