]>
git.scottworley.com Git - slidingtile/blob - sliding_tile_lib.cc
aee8380c421fe11036f4c9bc957cca971edf6eca
1 #include "sliding_tile_lib.h"
8 signed char adjacent
[BOARD_SIZE
][5] = {
27 bool Board::is_valid() const {
28 bool seen
[BOARD_SIZE
];
29 for (int i
= 0; i
< BOARD_SIZE
; i
++) {
33 for (int i
= 0; i
< BOARD_SIZE
; i
++) {
34 if (board
[i
] < 0 || board
[i
] >= BOARD_SIZE
|| seen
[board
[i
]]) {
37 seen
[board
[i
]] = true;
40 // Redundant because pigeon-hole-principle, but check anyway
41 for (int i
= 0; i
< BOARD_SIZE
; i
++) {
50 std::istream
& operator>>(std::istream
& is
, Board
& board
) {
51 for (int i
= 0; i
< BOARD_SIZE
; i
++) {
53 is
.setstate(std::istream::failbit
);
56 if (i
> 0 && is
.get() != ',') {
57 is
.setstate(std::istream::failbit
);
62 board
.board
[i
] = numeric
;
64 if (!board
.is_valid()) {
65 is
.setstate(std::istream::failbit
);
70 std::ostream
& operator<<(std::ostream
& os
, const Board
& board
) {
71 for (int i
= 0; i
< BOARD_SIZE
; i
++) {
75 os
<< int(board
.board
[i
]);
80 signed char Board::hole() const {
81 for (int i
= 0; i
< BOARD_SIZE
; i
++) {
86 throw std::runtime_error("Board with no hole");
89 InvertedBoard
Board::invert() const {
91 for (int i
= 0; i
< BOARD_SIZE
; i
++) {
92 inv
.pos
[board
[i
]] = i
;
97 int Board::distance(const Board
& o
) const {
98 return distance(o
.invert());
101 int Board::distance(const InvertedBoard
& invo
) const {
103 for (int i
= 0; i
< BOARD_SIZE
; i
++) {
104 dist
+= std::abs(i
% BOARD_DIM
- invo
.pos
[board
[i
]] % BOARD_DIM
) +
105 std::abs(i
/ BOARD_DIM
- invo
.pos
[board
[i
]] / BOARD_DIM
);