def aStar(initialState, goalState): closed = set() openedIPQ = IndexedPriorityQueue.IndexedPriorityQueue() currentIPQ = puzzle.Puzzle(arguments, initialState, goalState, 0) currentIPQ.compute() openedIPQ.append(currentIPQ) while hasAtLeastOneElem(openedIPQ.opened): currentIPQ = openedIPQ.pop() if currentIPQ.puzzle == goalState: traceRoute(currentIPQ, openedIPQ.allTimeOpened, openedIPQ.maxSameTimeOpened) for n in currentIPQ.getNeighbours(): neighbour = puzzle.Puzzle(arguments, n, goalState, currentIPQ.g + 1) neighbour.compute() neighbour.parent = currentIPQ if hashPuzzle( neighbour.puzzle, neighbour.f ) in closed or openedIPQ.gotOpenedWithLowerCost(neighbour): continue openedIPQ.append(neighbour) closed.add(hashPuzzle(currentIPQ.puzzle, currentIPQ.f)) helpers.exit("no solution found")
def new_puzzle(): print('Generating a new puzzle ...') temp_puzzle = puzzle.Puzzle( random.randint(puzzle.MINIMUM_FILLED_TUBE, puzzle.MAXIMUM_FILLED_TUBE), random.randint(1, 2)) while any((len(set(tube)) < 2 and len(tube) > 0) for tube in temp_puzzle._Puzzle__puzzle): temp_puzzle = puzzle.Puzzle( random.randint(puzzle.MINIMUM_FILLED_TUBE, puzzle.MAXIMUM_FILLED_TUBE), random.randint(1, 2)) return temp_puzzle
def main(): pz = puzzle.Puzzle(3) pz.generateRandomPuzzle(10) pz.printPuzzle() s = ids.AI(pz) print('Ô trống sẽ di chuyển theo hướng: ', s.depthLimited(5))
def makePuzzle(x): customPuzzle = [] print " Enter your " + str(x) + ", use a zero to represent the blank" get = raw_input(' Enter the first row, use space or tabs between numbers ') temp = map(int, re.split(', | ', get)) for num in temp: customPuzzle.append(num) get = raw_input(' Enter the second row, use space or tabs between numbers ') temp = map(int, re.split(', | ', get)) for num in temp: customPuzzle.append(num) get = raw_input(' Enter the third row, use space or tabs between numbers ') temp = map(int, re.split(', | ', get)) for num in temp: customPuzzle.append(num) if puzzle.edge > 3: get = raw_input(' Enter the fourth row, use space or tabs between numbers ') temp = map(int, re.split(', | ', get)) for num in temp: customPuzzle.append(num) if puzzle.edge > 4: get = raw_input(' Enter the fifth row, use space or tabs between numbers ') temp = map(int, re.split(', | ', get)) for num in temp: customPuzzle.append(num) if x is "goal": return puzzle.makeAnswer(customPuzzle) else: return puzzle.Puzzle(customPuzzle)
def test_only_one_root(self): small_puzzle = P.Puzzle(["1", "2"], [["a", "b"]], []) sx = small_puzzle.X root_rule_form = (And( Or( And(sx[0,0,0], ~sx[0,0,1]), And(~sx[0,0,0], sx[0,0,1])), Or( And(sx[0,1,0], ~sx[0,1,1]), And(~sx[0,1,0], sx[0,1,1])))) self.assertTrue(And(*small_puzzle.only_one_root()).equivalent(root_rule_form))
def parse(f): """Read a file and return the corresponding grid :param f: File object to read from :returns: Corresponding grid read from f :rtype: Puzzle """ n = -1 k = -1 grid = [] for line in f: line_ = line.split("#")[0].strip() if not line_: continue if not n: raise SyntaxError("Too many rows: {}".format(line)) if n == -1: n = int(line) if n < 1: raise ValueError("Size of puzzle must be positive") k = n continue row = line_.split() if len(row) != k: raise SyntaxError("Too many columns: {}".format(line)) grid.append([int(x) for x in row]) final_grid = np.array(grid) if not np.array_equal(np.sort(final_grid.flatten()), np.arange(k ** 2)): raise ValueError("Invalid grid:\n{}".format("\n".join(str(s) for s in grid))) return puzzle.Puzzle(np.array(grid))
def test_part_two(self): "Test part two example of Puzzle object" # 1. Create Puzzle object from text myobj = puzzle.Puzzle(part2=True, text=aoc_23.from_text(PART_TWO_TEXT)) # 2. Check the part two result self.assertEqual(myobj.part_two(verbose=True), PART_TWO_RESULT)
def test_empty_init(self): "Test the default Puzzle creation" # 1. Create default Puzzle object myobj = puzzle.Puzzle() # 2. Make sure it has the default values self.assertEqual(myobj.part2, False) self.assertEqual(myobj.text, None)
def test_part_one(self): "Test part one example of Puzzle object" # 1. Create Puzzle object from text myobj = puzzle.Puzzle(part2=False, text=aoc_23.from_text(PART_ONE_TEXT)) # 2. Check the part two result self.assertEqual(myobj.part_one(verbose=False), PART_ONE_RESULT)
def print_puzzle(self): if has_print: selection = self.tree.get_selection() (model, iter) = selection.get_selected() location = self.model.get_location_iter(iter) puz = puzzle.Puzzle(location) pr = printing.PuzzlePrinter(puz) pr.print_puzzle(self.win) else: self.notify('Printing support is not available (need GTK 2.10+).')
def run(file): f = file p = puzzle.Puzzle(f) sol = p.init_solution() search = a_star.AStarSearch(p, sol) start = datetime.now() search.search() stop = datetime.now() print("runtime: ", stop - start) print('===================================')
def solve(input, loglevel, debugToFile, singleStep): """ Solve a puzzle specified by one or more INPUT constraints files. """ if debugToFile: loglevel = logging.DEBUG logFileName = 'debug.log' if os.path.exists(logFileName): os.remove(logFileName) logging.basicConfig(format='%(message)s', level=loglevel, filename='debug.log') else: logging.basicConfig( format='%(message)s', level=loglevel) # filename='output.txt' for grepping on Windows p = puzzle.Puzzle() if singleStep and singleStep >= 2: p.techniqueCallback = showStep if singleStep and singleStep >= 1: p.solutionCallback = showSolutionChange for i in input: p.addConstraints(i) logging.info("Puzzle:") logging.info(p) logging.info("\nSolving...") p.solve() # Report stats but not using logging - so it's available to regression tests. if loglevel <= logging.INFO: click.echo("\nTook %s reduction passes." % p.stats['passes']) if 'plies' in p.stats: click.echo( "After the first %s passes, explored the solution tree to %s plies." % (p.stats['firstPasses'], p.stats['plies'])) techniques = sorted(p.stats['techniques'].items(), key=lambda kv: -kv[1]) click.echo( "Used these techniques: %s" % ', '.join([t[0] + ' (' + str(t[1]) + 'x)' for t in techniques])) logging.info("") # separator if p.isSolved(): click.echo("Solved:") click.echo(str(p.solution)) else: if p.isUnsolvable(): click.echo("Can't solve because it doesn't appear to be solvable.") click.echo("(Error in creation or transcription? Or my bad?)") else: click.echo("Can't solve.") click.echo("Best solution:") click.echo(p)
def work_on_current_block(task_solver = solvers.nn_solver, puzzle_solver = puzzle.solve_puzzle): # Get current block chain blockinfo = getblockinfo() block_idx = blockinfo['block'] task_string = blockinfo['task'] puzzle_string = blockinfo['puzzle'] excluded = blockinfo['excluded'] balances = blockinfo['balances'] subdir = os.path.join('..', 'chain_submissions', str(block_idx)) os.makedirs(subdir, exist_ok = True) task_solution_path = os.path.join(subdir, 'task.sol') puzzle_solution_path = os.path.join(subdir, 'puzzle.desc') submitted_path = os.path.join(subdir, 'submitted') print("Working on block", block_idx) if str(team_id) in excluded: print("Note that we are excluded from working on this block!") print(" Balance:", balances[str(team_id)]) if os.path.exists(submitted_path): print(" Already submitted to this block") return # Parse puzzles t = task.Task.from_string(task_string) p = puzzle.Puzzle(puzzle_string) # Solve puzzles print(" solving...") task_solution = task_solver(t) print(" ...done with task (time {})".format(task_solution.time())) puzzle_solution = puzzle_solver(p) print(" ...done with puzzle") # Print puzzles task_solution.to_file(task_solution_path) with open(puzzle_solution_path, 'w') as f: f.write(puzzle_solution.to_string()) # Submit puzzles print(" submitting...") call_client(['submit', str(block_idx), str(task_solution_path), str(puzzle_solution_path)]) print(" ...submitted!") with open(submitted_path, 'w') as f: f.write('Submitted\n')
def xyCostHeuristic(lst, goal): p = puzzle.Puzzle(lst, goal) #Row moves aspect of the heurstic. rowMoves is the minimum number of row #moves required for each element to be in its goal row. (_, rowMoves) = p.aStarManhattanHeuristic(1) #Column moves aspect of the heurstic. columnMoves is the minimum number of #column moves required for each element to be in its goal column. (_, columnMoves) = p.aStarManhattanHeuristic(2) return rowMoves + columnMoves
def idaStar(initialState, goalState): current = puzzle.Puzzle(arguments, initialState, goalState, 0) current.compute() threshold = current.f while True: res = idaSearch(current, goalState, 0, threshold) if res == 0: helpers.exit("") if res > sys.maxsize: helpers.exit("no solution found") threshold = res
def test_three_moves(self): "Test the Puzzle object creation from text that needs three moves" # 1. Create Puzzle object from text myobj = puzzle.Puzzle(text=aoc_23.from_text(EXAMPLE_THREE_MOVES)) # 2. Make sure it has the expected values self.assertEqual(myobj.part2, False) self.assertEqual(len(myobj.text), 5) # 3. Check methods self.assertEqual(myobj.burrow.positions(), ".....D.D.A..ABBCC..") self.assertEqual(myobj.organize(), 7008)
def test_text_init(self): "Test the Puzzle object creation from text" # 1. Create Puzzle object from text myobj = puzzle.Puzzle(text=aoc_23.from_text(EXAMPLE_TEXT)) # 2. Make sure it has the expected values self.assertEqual(myobj.part2, False) self.assertEqual(len(myobj.text), 5) # 3. Check methods self.assertEqual(myobj.burrow.positions(), "...........BACDBCDA") self.assertEqual(myobj.organize(), 12521)
def test_no_moves(self): "Test the Puzzle object creation from text that is complete" # 1. Create Puzzle object from text myobj = puzzle.Puzzle(text=aoc_23.from_text(EXAMPLE_NO_MOVES)) # 2. Make sure it has the expected values self.assertEqual(myobj.part2, False) self.assertEqual(len(myobj.text), 5) # 3. Check methods self.assertEqual(myobj.burrow.positions(), "...........AABBCCDD") self.assertEqual(myobj.organize(), 0)
def test_one_move(self): "Test the Puzzle object creation from text that needs only one move" # 1. Create Puzzle object from text myobj = puzzle.Puzzle(text=aoc_23.from_text(EXAMPLE_ONE_MOVE)) # 2. Make sure it has the expected values self.assertEqual(myobj.part2, False) self.assertEqual(len(myobj.text), 5) # 3. Check methods self.assertEqual(myobj.burrow.positions(), ".........A..ABBCCDD") self.assertEqual(myobj.organize(), 8)
def main(script, *args): if len(sys.argv) != 3 and len(sys.argv) != 4: print "Error in arguments!" sys.exit() grid = Grid.Grid(3) game = puzzle.Puzzle(3, sys.argv[1], grid) start_position = convert_arguments(sys.argv[2]) game.solve_it(start_position) grid.openGrid() game.build_results() time.sleep(10) grid.closeGrid()
def getDefault(): if puzzle.size == 9: y = input("Please select a puzzle difficulty between 0 and 11: ") if y in range(0, 12): default = puzzle.Puzzle(ninepuzzle[y]) else: print "incorrect input" return getDefault() elif puzzle.size == 16: y = input("Please select a puzzle difficulty between 0 and 3: ") if y in range(0, 4): default = puzzle.Puzzle(fifteenpuzzle[y]) else: print "incorrect input" return getDefault() elif puzzle.size == 25: y = input("Please select a puzzle difficulty between 0 and 3: ") if y in range(0, 4): default = puzzle.Puzzle(twentyfourpuzzle[y]) else: print "incorrect input" return getDefault() return default
def test_seven_moves(self): "Test the Puzzle object creation from text that needs three moves" # 1. Create Puzzle object from text myobj = puzzle.Puzzle(text=aoc_23.from_text(EXAMPLE_SEVEN_MOVES)) myobj.part2 = True # 2. Make sure it has the expected values self.assertEqual(myobj.part2, True) self.assertEqual(len(myobj.text), 7) # 3. Check methods self.assertEqual(myobj.burrow.positions(), "AA.......AD.DDABBBBCCCC...D") self.assertEqual(myobj.organize(), 25016)
def part_two(args, input_lines): "Process part two of the puzzle" # 1. Create the puzzle solver solver = puzzle.Puzzle(part2=True, text=input_lines) # 2. Determine the solution for part two solution = solver.part_two(verbose=args.verbose, limit=args.limit) if solution is None: print("There is no solution") else: print("The solution for part two is %s" % (solution)) # 3. Return result return solution is not None
def main(): n = 8 if len(sys.argv) == 2 and isSquareRoot(int(sys.argv[1]) + 1): n = int(sys.argv[1]) initMode = input( "\nWelcome to Bertie Woosters " + str(n) + "-puzzle solver.\n" + "Type '1' to use a default puzzle, or '2' to enter your own puzzle, or '3' to generate random puzzle.\n" ) print("----------------------------------------\n") p = puzzle.Puzzle(int(math.sqrt(n + 1))) if initMode == '1': p.deffault() elif initMode == '2': p.setPuzzle() elif initMode == '3': p.randomPuzzle() else: sys.exit(0) print("This is the puzzle:") p.showPuzzle() print("----------------------------------------") print( "\nEnter your choice of algorithm:\n 1. Uniform Cost Search.\n 2. A* with the Misplaced Tile heuristic.\n" " 3. A* with the Manhattan distance heuristic.") mode = input() print("----------------------------------------\n") s = search.Search(p) goal = s.run(mode) print("----------------------------------------\n") if goal is not None: print( "\n To solve this problem the search algorithm expanded a total of " + str(s.numOfNodes) + " nodes.") print( " The maximum number of nodes in the queue at any one time was " + str(s.maxQueueSize)) print(" The depth of the goal node was " + str(s.depth)) else: print("\n Can not find the goal!")
def load_population(old_pop=False): """ Load an old population or a new one. If old_pop is False, the new \ population will be loaded from config.population_file_base. :param bool old_pop: loading the old population saved at \ config.population_file_saved :return: A [Puzzle](doc/puzzle.md) object. """ if old_pop: f = _load_file(config.population_file_saved) if f != None: return f inds = ind.get_population() corner = [i for i in inds if i[1].count(0) == 2] border = [i for i in inds if i[1].count(0) == 1] inside = [i for i in inds if i[1].count(0) == 0] return puzzle.Puzzle((corner, border, inside))
def test_alt_clueset(self): alt =[ { "type": "SAME", "vals": ["Batman", "ball"] }, { "type": "XAWAY", "vals": ["ball", "Starbuck", 2] }, { "type": "SAME", "vals": ["Dibii", "laser"] } ] self.assertEqual(self.ex_puzzle.alt_clueset(), alt) no_puzzle = P.Puzzle([], [], []) self.assertFalse(no_puzzle.alt_clueset())
def idaSearch(current, goalState, g, threshold): current.compute() if current.f > threshold: return current.f if current.puzzle == goalState: traceRoute(current) return 0 min = sys.maxsize for n in current.getNeighbours(): neighbour = puzzle.Puzzle(arguments, n, goalState, g + 1) neighbour.parent = current res = idaSearch(neighbour, goalState, g + 1, threshold) if res == 0: traceRoute(neighbour) return 0 if res < min: min = res return min
def do_open_file(self, fname, ask=True): if self.puzzle: self.write_puzzle() if self.clock_running: self.activate_clock(False) self.set_puzzle(puzzle.Puzzle(fname), ask) self.control = controller.PuzzleController(self.puzzle) self.setup_controller() self.clue_widget.set_controller(self.control) self.puzzle_widget.set_puzzle(self.puzzle, self.control) self.load_list(ACROSS) self.load_list(DOWN) self.enable_controls(True, self.puzzle.is_locked()) self.config.add_recent(self.puzzle) self.update_recent_menu() self.idle_event() self.letter_update(0, 0)
def read_file(file, check): """Get puzzle file from user, validate it, and return a Puzzle object and the name of the file the puzzle came from. :param file: name of file to check :param check: True if the user is only checking if the puzzle is solvable. This suppresses the warning that the puzzle doesn't have enough clues. :return: Puzzle object and file name on success, (None, None) either on quit or when less than 17 clues and the --check flag was passed. """ while True: try: if not file: print('Type "exit" at the prompt to quit.') file_name = input('Puzzle file name: ') else: file_name = file file = None if file_name == 'exit': print('User quit program.') return None, None puzzle_string = parse_file(file_name) if puzzle_string: break except ClueError as err: if check: print('{} is unsolvable'.format(err.file_name)) return None, None # quits run else: print('{} is an unsolvable puzzle. It has {} clues.\n' 'There are no valid sudoku puzzles with fewer than 17 clues.' .format(err.file_name, err.num_clues)) except OSError: print('File {} not found.'.format(file_name)) puzzle = pzl.Puzzle(puzzle_string) return puzzle, file_name
return total; def call(call, board): return [["X" if c == call else c for c in row] for row in board] def one(INPUT): calls, boards = process_input(INPUT) for c in calls: for b_i in range(len(boards)): boards[b_i]=call(c, boards[b_i]) if isWinner(boards[b_i]): return calcScore(boards[b_i]) * c; def two(INPUT): calls, boards = process_input(INPUT) winners = set() for c in calls: for b_i in range(len(boards)): boards[b_i]=call(c, boards[b_i]) if isWinner(boards[b_i]): # print('\n'.join([str(row) for row in boards[b_i]])) winners.add(b_i) # print() if len(winners) == len(boards): return calcScore(boards[b_i]) * c; p = puzzle.Puzzle("4") p.run(one, 0) p.run(two, 0)