Commits

shl...@27f4d2be-69b7-b1af-7dc8-71755b09f50e  committed fe7f260

Implement the board parser.

  • Participants
  • Parent commits 4e26a51

Comments (0)

Files changed (2)

File hitori-solver-in-ruby/hitori-solver.rb

     end
     class CellShouldBeDifferentColor < UnsolvableException
     end
+    class ParseException < RuntimeError
+    end
+    class DimsParseException < ParseException
+    end
 
     module Offset_Module
         class OffsetsList
             end
         end
 
+        def self.parse(board_string)
+            lines = board_string.split(/\n/)
+            next_line = 0
+            dims = lines[next_line]
+            next_line += 1
+            if dims =~ /^(\d+)\*(\d+)\s*\z/ then
+                height, width = $1.to_i, $2.to_i
+            else
+                raise DimsParseException, "Could not parse dimensions at line 1";
+            end
+
+            contents = []
+            for y in 1 .. height do
+                line = lines[next_line]
+                next_line += 1
+                out_line = []
+                for x in 0 .. (width-1) do
+                    if line.sub!(/^\[(\d+)(W|B|U|)\]\s*/, "")
+                        id, status = $1.to_i(), $2
+                        if (status == "U" or status == "")
+                            out_line << id
+                        else
+                            out_line << [id, 
+                                (status == "W" ? 
+                                 HitoriSolver::Cell::WHITE :
+                                 HitoriSolver::Cell::BLACK)]
+                        end
+                    else
+                        raise CellParseException, "Could not parse cell at line #{next_line}";
+                    end
+                end
+                contents << out_line
+            end
+
+            return contents
+        end
+
     end
 
     class Move

File hitori-solver-in-ruby/t/parse-board.rb

     end
 
 end
+
+describe "parse the board" do
+
+    before (:each) do
+
+        @contents = [
+            [[2,HitoriSolver::Cell::BLACK],[1,HitoriSolver::Cell::WHITE],3,2,4,],
+            [[4,HitoriSolver::Cell::WHITE],[5,HitoriSolver::Cell::WHITE],3,2,2,],
+            [[3,HitoriSolver::Cell::WHITE],[4,HitoriSolver::Cell::BLACK],[2,HitoriSolver::Cell::WHITE],5,1,],
+            [[1,HitoriSolver::Cell::WHITE],[4,HitoriSolver::Cell::WHITE],[3,HitoriSolver::Cell::BLACK],[3,HitoriSolver::Cell::WHITE],2,],
+            [[2,HitoriSolver::Cell::WHITE],[5,HitoriSolver::Cell::BLACK],[1,HitoriSolver::Cell::WHITE],[4,HitoriSolver::Cell::WHITE],3,],
+]
+
+    end
+    
+    it "should parse the string correctly" do
+
+        got_contents = HitoriSolver::Board.parse(<<"EOF")
+5*5
+[2B] [1W] [3]  [2U] [4]
+[4W] [5W] [3]  [2]  [2U]
+[3W] [4B] [2W] [5]  [1]
+[1W] [4W] [3B] [3W] [2]
+[2W] [5B] [1W] [4W] [3U]
+EOF
+
+        got_contents.should == @contents
+    end
+
+end
+