class TestBacktrackingSolver(TestCase): def init_solver(self, matrix): self.puzzle = Board(matrix) self.rules = RuleHandler() self.solver = BacktrackingSolver(self.rules) def make_matrix(self, matrix): return [int(i) for i in matrix.replace('_', '0').split()] def test_reduce_candidates(self): matrix = self.make_matrix(''' 3 4 1 2 _ 2 3 _ _ 3 _ _ _ _ 4 3''') self.init_solver(matrix) solution = next(self.solver.solve(self.puzzle)) cell = solution.get_cell(0, 1) assert 1 == cell cell = solution.get_cell(0, 2) assert 4 == cell def test_solve_simple_one_cycle(self): matrix = self.make_matrix(''' 3 4 1 2 _ 2 3 _ _ 3 2 1 2 1 4 3''') expected = self.make_matrix(''' 3 4 1 2 1 2 3 4 4 3 2 1 2 1 4 3''') self.init_solver(matrix) solution = next(self.solver.solve(self.puzzle)) assert is_solved(solution) assert expected == solution.matrix def test_solve_simple_two_cycles(self): matrix = self.make_matrix(''' _ 4 _ 2 _ 2 3 _ _ 3 2 1 2 1 4 3''') expected = self.make_matrix(''' 3 4 1 2 1 2 3 4 4 3 2 1 2 1 4 3''') self.init_solver(matrix) solution = next(self.solver.solve(self.puzzle)) assert is_solved(solution) assert expected == solution.matrix def test_solve_with_iteration(self): matrix = self.make_matrix(''' 3 _ _ 2 _ 2 3 _ _ 3 2 _ 2 _ _ 3''') solution1 = self.make_matrix(''' 3 4 1 2 1 2 3 4 4 3 2 1 2 1 4 3''') solution2 = self.make_matrix(''' 3 1 4 2 4 2 3 1 1 3 2 4 2 4 1 3''') self.init_solver(matrix) solution = next(self.solver.solve(self.puzzle)) assert is_solved(solution) assert solution.matrix in [solution1, solution2] def test_solve_many_iterations(self): matrix = self.make_matrix(''' 3 _ _ _ _ _ _ _ _ _ _ _ _ _ _ 3''') self.init_solver(matrix) solution = next(self.solver.solve(self.puzzle)) assert is_solved(solution) def test_solve_many_iterations3x3(self): matrix = self.make_matrix(''' 3 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 3''') self.init_solver(matrix) iterator = iter(self.solver.solve(self.puzzle)) solution1 = next(iterator) assert is_solved(solution1) solution2 = next(iterator) assert is_solved(solution2) assert solution1.matrix != solution2.matrix
infile_parser = PARSER_FILE_EXT_MAPPING[infile_ext]() outfile_parser = PARSER_FILE_EXT_MAPPING[outfile_ext]() text_parser = TextParser() try: puzzle = infile_parser.loads(args.infile.read()) except ParseError as e: print(e) exit(1) rules = RuleHandler() solver = BacktrackingSolver(rules) if args.display: print('Puzzle:') print(text_parser.dumps(puzzle)) try: solution = next(solver.solve(puzzle)) except StopIteration: print('No solution could be found.') exit(2) if args.display: print('Solution:') print(text_parser.dumps(solution)) else: print('Puzzle solved.') args.outfile.write(outfile_parser.dumps(solution))