]> git.scottworley.com Git - slidingtile/commitdiff
Board input
authorScott Worley <scottworley@scottworley.com>
Thu, 31 Dec 2015 08:11:14 +0000 (00:11 -0800)
committerScott Worley <scottworley@scottworley.com>
Thu, 31 Dec 2015 08:11:14 +0000 (00:11 -0800)
sliding_tile_lib.cc
sliding_tile_lib.h
sliding_tile_lib_test.cc

index 4b422c1721da721020713f6410a93b7a5f283edf..a4d522e6745a99507612540f9664ed3ab6f9a8ee 100644 (file)
@@ -1,5 +1,7 @@
 #include "sliding_tile_lib.h"
 
+#include <istream>
+
 signed char adjacent[BOARD_SIZE][5] = {
   1,   4,   -1,  -1,  -1,
   0,   2,   5,   -1,  -1,
@@ -18,3 +20,20 @@ signed char adjacent[BOARD_SIZE][5] = {
   10,  13,  15,  -1,  -1,
   11,  14,  -1,  -1,  -1,
 };
+
+std::istream& operator>>(std::istream& is, Board& board) {
+  for (int i = 0; i < BOARD_SIZE; i++) {
+    if (!is.good()) {
+      is.setstate(std::istream::failbit);
+      break;
+    }
+    if (i > 0 && is.get() != ',') {
+      is.setstate(std::istream::failbit);
+      break;
+    }
+    int numeric;
+    is >> numeric;
+    board[i] = numeric;
+  }
+  return is;
+}
index 7e6004b4aad5b0a6b77140d5c957e986a1afb04b..8967324fb745eba07d8cd98743edac3ae597757b 100644 (file)
@@ -1,8 +1,14 @@
 #ifndef _SLIDING_TILE_LIB_H
 #define _SLIDING_TILE_LIB_H
 
+#include <istream>
+
 const int BOARD_DIM = 4;
 const int BOARD_SIZE = BOARD_DIM * BOARD_DIM;
+
+typedef signed char Board[BOARD_SIZE];
+std::istream& operator>>(std::istream& is, Board& board);
+
 extern signed char adjacent[BOARD_SIZE][5];
 
 #endif /* _SLIDING_TILE_LIB_H */
index 20508968737bbca30855fa9ecbf2dec7128e3d4a..0bbaec3a85a4e89e31026684a4756a778ee42618 100644 (file)
@@ -32,3 +32,26 @@ TEST(Adjacency, Adjacency) {
     EXPECT_THAT(actual, testing::UnorderedElementsAreArray(expected));
   }
 }
+
+TEST(Board, GoodInput) {
+  std::istringstream is{"15,14,9,13,3,1,12,8,0,11,6,4,7,5,2,10"};
+  Board b;
+  is >> b;
+  EXPECT_FALSE(is.fail());
+  EXPECT_TRUE(is.eof());
+  EXPECT_THAT(b, testing::ElementsAreArray({15,14,9,13,3,1,12,8,0,11,6,4,7,5,2,10}));
+}
+
+TEST(Board, ShortInput) {
+  std::istringstream is{"15,14,9,13,3,1,12,8,0,11,6,4,7,5,2"};
+  Board b;
+  is >> b;
+  EXPECT_TRUE(is.fail());
+}
+
+TEST(Board, NonNumericInput) {
+  std::istringstream is{"15,14,foo,13,3,1,12,8,0,11,6,4,7,5,2,10"};
+  Board b;
+  is >> b;
+  EXPECT_TRUE(is.fail());
+}