import java.util.Arrays;

/**
 * A simple board is a specialization of Board where we can represent it as a
 * 1-D array rather than a 2-D matrix. This is possible due to the placement
 * requirements of a queen (only one per row)
 * 
 * A special value, <code>UNPLACED</code>, indicates that a queen has not been
 * placed in a specified row. When a value, <em>v</em>, at index <em>i</em>
 * is in the range <code>[0, size)</code> then a queen has been placed at the
 * specified column, <em>v</em>, at row, <em>i</em>.
 * 
 * @author Professor Killian
 *
 */
public class SimpleBoard implements Board {
	private int size;
	private int[] board;
	private static final int UNPLACED = -1;

	/**
	 * Constructs a new Board of size <em>n</em>
	 * @param n the size of the Board
	 */
	public SimpleBoard(int n) {
		size = n;
		board = new int[n];
		Arrays.fill(board, UNPLACED);
	}

	@Override
	public boolean canPlace(int r, int c) {
		if (r < 0 || r >= size || c < 0 || c >= size) {
			throw new RuntimeException("Tried to place out of bounds");
		}
		// implicitly only allow one piece per row
		for (int i = 0; i < r; ++i) {
			// check if only piece in column
			if (board[i] == c) {
				return false;
			}
			if (board[i] == UNPLACED) {
				throw new RuntimeException("Tried to place a piece before permitted");
			}
			int deltaR = r - i;
			int deltaC = Math.abs(c - board[i]);
			if (deltaR == deltaC) {
				return false;
			}
		}
		return true;
	}

	@Override
	public void place(int r, int c) {
		board[r] = c;
	}

	@Override
	public void unplace(int r, int c) {
		board[r] = UNPLACED;
	}

	@Override
	public void print() {
		for (int loc : board) {
			for (int i = 0; i < loc; ++i) {
				System.out.print('.');
				System.out.print(' ');
			}
			System.out.print('*');
			System.out.print(' ');
			for (int i = loc + 1; i < size; ++i) {
				System.out.print('.');
				System.out.print(' ');
			}
			System.out.println();
		}
	}

	@Override
	public int size() {
		return size;
	}

}
