X-Git-Url: http://git.scottworley.com/slidingtile/blobdiff_plain/32688d85f745574d7bbf941985234458d2776cce..b18667f24728cb960b0c60fa55824062582278bf:/sliding_tile_lib.cc?ds=sidebyside diff --git a/sliding_tile_lib.cc b/sliding_tile_lib.cc index a4d522e..3b7806b 100644 --- a/sliding_tile_lib.cc +++ b/sliding_tile_lib.cc @@ -21,6 +21,29 @@ signed char adjacent[BOARD_SIZE][5] = { 11, 14, -1, -1, -1, }; +bool Board::is_valid() { + bool seen[BOARD_SIZE]; + for (int i = 0; i < BOARD_SIZE; i++) { + seen[i] = false; + } + + for (int i = 0; i < BOARD_SIZE; i++) { + if (board[i] < 0 || board[i] >= BOARD_SIZE || seen[board[i]]) { + return false; + } + seen[board[i]] = true; + } + + // Redundant because pigeon-hole-principle, but check anyway + for (int i = 0; i < BOARD_SIZE; i++) { + if (!seen[i]) { + return false; + } + } + + return true; +} + std::istream& operator>>(std::istream& is, Board& board) { for (int i = 0; i < BOARD_SIZE; i++) { if (!is.good()) { @@ -33,7 +56,10 @@ std::istream& operator>>(std::istream& is, Board& board) { } int numeric; is >> numeric; - board[i] = numeric; + board.board[i] = numeric; + } + if (!board.is_valid()) { + is.setstate(std::istream::failbit); } return is; }