def setUp(self): self.testSolver = solver.Solver() #Square test data self.testSquareComplete = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] self.testSquareHorizontalDuplicate = [[1, 2, 3], [5, 5, 6], [7, 8, 9]] self.testSquareVerticalDuplicate = [[1, 2, 4], [4, 5, 6], [7, 8, 9]] self.testSquareIncomplete = [['O', 2, 3], [4, 'O', 6], [7, 8, 9]] self.testSquareShort = [[5, 6], [7, 8, 9]] self.testSquareLong = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
def test_calcPercentStake(): player.Player.id = 0 opts["PLAYERS"] = [(1, i) for i in range(10)] s = solver.Solver(opts) assert s.calcPercentStake() == [ 0, 1 / 45, 2 / 45, 3 / 45, 4 / 45, 5 / 45, 6 / 45, 7 / 45, 8 / 45, 9 / 45 ]
def simulate(self, filename): """Start the simulation by calling the solver""" input_data = self.netHandler.readFile(self.pathToRessources + filename) schaltung = nt.Schaltung(input_data) schaltung.initInzidenzMatritzen() solver = solv.Solver(schaltung) self.solutionData = solver.simulate(self.t, self.t_steps)
def test_methods(self): "Test exploration between portal locations and other methods" # 1. Create an solver without a donut and then slap on a donut mysolver = solver.Solver() mysolver.donut = donut.Donut(text=from_text(test_donut.EXAMPLES[0])) # 2. Explore from all portal ends self.assertEqual(mysolver.explore_from((2, 8)), {(6, 10): 6}) # BC -> DE self.assertEqual(mysolver.explore_from((2, 13)), {(2, 15): 4}) # DE -> FG self.assertEqual(mysolver.explore_from((2, 15)), {(2, 13): 4}) # FG -> DE self.assertEqual(mysolver.explore_from((6, 10)), {(2, 8): 6}) # DE -> BC self.assertEqual(mysolver.explore_from((9, 2)), {(9, 6): 4, # AA -> BC (11, 12): 30, # AA -> FG (13, 16): 26}) # AA -> ZZ self.assertEqual(mysolver.explore_from((11, 12)), {(13, 16): 6, # FG -> ZZ (9, 2): 30, # FG -> AA (9, 6): 32}) # FG -> BC self.assertEqual(mysolver.explore_from((13, 16)), {(11, 12): 6, # ZZ -> FG (9, 2): 26, # ZZ -> AA (9, 6): 28}) # ZZ -> BC # 3. Compute and check direct portal paths mysolver.portal_paths = mysolver.get_direct_paths_between_portals() self.assertEqual(len(mysolver.portal_paths), 5) self.assertEqual(sorted(mysolver.portal_paths.keys()), ['AA', 'BC', 'DE', 'FG', 'ZZ']) self.assertEqual(len(mysolver.portal_paths['AA']), 3) self.assertEqual(sorted([path.steps for path in mysolver.portal_paths['AA']]), [4, 26, 30]) self.assertEqual(sorted([path.steps for path in mysolver.portal_paths['BC']]), [1, 1, 4, 6, 28, 32]) self.assertEqual(sorted([path.steps for path in mysolver.portal_paths['DE']]), [1, 1, 4, 6]) self.assertEqual(sorted([path.steps for path in mysolver.portal_paths['FG']]), [1, 1, 4, 6, 30, 32]) self.assertEqual(sorted([path.steps for path in mysolver.portal_paths['ZZ']]), [6, 26, 28]) # 4. Compute and check graph mysolver.graph = mysolver.portal_paths_to_graph() self.assertEqual(len(mysolver.graph.edges), 22) # 5. Test solving the graph mysolver.solve_donut_maze() self.assertEqual(len(mysolver.path), 8) self.assertEqual(mysolver.cost, 23) # 6. Test part2 graph generation mysolver.part2 = True mysolver.graph = mysolver.portal_paths_to_graph(depth=1) self.assertCountEqual(Counter([(_.start[0], _.end[0]) for _ in mysolver.graph.edges]), {(0, 0): 22}) mysolver.graph = mysolver.portal_paths_to_graph(depth=2) self.assertCountEqual(Counter([(_.start[0], _.end[0]) for _ in mysolver.graph.edges]), {(0, 0): 12, (1, 1): 6, (0, 1): 3, (1, 0): 3}) mysolver.graph = mysolver.portal_paths_to_graph(depth=3) self.assertCountEqual(Counter([(_.start[0], _.end[0]) for _ in mysolver.graph.edges]), {(0, 0): 12, (1, 1): 6, (2, 2): 6, (0, 1): 3, (1, 2): 3, (1, 0): 3, (2, 1): 3})
def restart(self, size, mines): self.solving = False self.lastSolvedTile = (-1, -1) pygame.time.set_timer(pygame.USEREVENT, 0) # turn off the timer self.game.reset() self.game.set_size(size) self.size = size self.game.set_mines(mines) self.mines = mines self.failed_tile = (-1, -1) self.solver = solver.Solver(self.game) self.game.begin()
def test_text_init(self): "Test the Solver object creation from text" # 1. Create Solver object from text myobj = solver.Solver(text=aoc_11.from_text(EXAMPLE_TEXT)) # 2. Make sure it has the expected values self.assertEqual(myobj.part2, False) self.assertEqual(len(myobj.text), 4) # 3. Check methods self.assertEqual(myobj.number_moves(), 11)
def test(): for board in configure.BOARD_MAP.values(): missing_count = len(board.not_on) print '-----------------' print missing_count total = 1 if missing_count == 10 else 8 counts = [] for i in range(total): s = solver.Solver(board) s.solve() print s.state_visited_count counts.append(s.state_visited_count) print 'avg:', sum(counts) / len(counts)
def __init__(self, puzzle_variant): self.piece_set = Piece_set(puzzle_variant) self.center_view = setup.setup_center_view(self.piece_set) setup.setup_drawer_views(self.piece_set) self.solver = solver.Solver(puzzle_variant) self.show_drawer_animation = setup.setup_show_drawer_animation() self.solved_tray_piece = None self.tray_piece_transforms = [] self.tray_piece_transforms_index = -1 data.hud_layer.set_title(str(puzzle_variant.name).replace('_', ' '))
def setUp(self): self.testSolver = solver.Solver() #Vertical test data self.testVerticalRowComplete = [[1], [2], [3], [4], [5], [6], [7], [8], [9]] self.testVerticalRowDuplicate = [[1], [2], [3], [5], [5], [6], [7], [8], [9]] self.testVerticalRowIncomplete = [['O'], [2], [3], [4], ['O'], [6], [7], [8], [9]] self.testVerticalRowShort = [[5], [6], [7], [8], [9]] self.testVerticalRowLong = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
def run(typ,rand,sbd,d,tnumber): try: dname = str(typ)+"_"+str(rand)+"_"+str(sbd)+"_"+str(d)+"_"+str(tnumber) pickle.dump(([[[i for i in range(typ)]]],[[typ]]), open(dname+".bounds","wb"),-1) pickle.dump([],open(dname+"true.state","wb"),-1) pickle.dump([],open(dname+"true.reward","wb"),-1) MEANS = np.array([i*1.0/(typ-1) for i in range(typ)]) STDS = np.array([1.0/(6*(typ-1)) for i in range(typ)]) if rand: MEANS = np.array([np.random.uniform() for i in range(typ)]) pickle.dump((typ,MEANS,STDS,d), open(dname+"subsolve.dat","wb"),-1) env = gym.make('fish-v0') env.initialize(types=typ,sbdepth=sbd,days=d,means=MEANS,discretize=False,stds=STDS) pickle.dump([],open(dname+"true.state","wb"),-1) pickle.dump([],open(dname+"true.reward","wb"),-1) reward = 0 s0 = state.State([parts(env.reset())],dname) sol = solver.Solver(s0,.95,1.02,dname) for i in range(d): a = sol.step() s, r, done, _ = env.step(a) sol.update([parts(s)]) reward += r #input("Continue:") if os.path.getsize(dname+"true.state") > 0 and os.path.getsize(dname+"true.reward") > 0: S = pickle.load(open(dname+"true.state","rb")) R= pickle.load(open(dname+"true.reward","rb")) else: S = [] R = [] S.append(s) R.append(r) pickle.dump(S,open(dname+"true.state","wb"),-1) pickle.dump(R,open(dname+"true.reward","wb"),-1) #print("ACTUAL FISH:",s) #print("ACTUAL REWARD",r) #print("FINAL REWARD: ",reward) pickle.dump(reward,open(dname+".final","wb"),-1) except: traceback.print_exc(file=open(dname+".error","w"))
def part_two(args, input_lines): "Process part two of the puzzle" # 1. Create the puzzle solver two = solver.Solver(part2=True, text=input_lines) # 2. Determine the solution for part two solution = two.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 part_two(args, input_lines): "Process part two of the puzzle" # 1. Create the keymaster clortho = solver.Solver(text=input_lines, part2=True) # 2. Get the maximum of the amplifiers without feedback solution, _ = clortho.get_all_keys(verbose=args.verbose) if solution is None: print("The keymaster could not solve the vault") else: print("The keymaster collected all the keys in %d steps" % (solution)) # 3. Return result return solution is not None
def test_p1e0_solve(self): "Test Solver object creation with text of part 1 example 0" # 1. Create Intcode obhect with values mysolver = solver.Solver(text=from_text(test_vault.EXAMPLES[0])) # 2. Make sure it has the specified values self.assertEqual(mysolver.vault.rows, 3) self.assertEqual(mysolver.vault.cols, 9) self.assertEqual(len(mysolver.key_paths), 3) # 3. Check methods solution = mysolver.get_all_keys() self.assertEqual(solution[0], 8) self.assertEqual(solution[1], [solver.ORIGIN_KEY, 'a', 'b'])
def test_p1e4_init(self): "Test Solver object creation with text of part 1 example 4" # 1. Create Intcode obhect with values mysolver = solver.Solver(text=from_text(test_vault.EXAMPLES[4])) # 2. Make sure it has the specified values self.assertEqual(mysolver.vault.rows, 6) self.assertEqual(mysolver.vault.cols, 24) self.assertEqual(len(mysolver.key_paths), 10) # 3. Check methods solution = mysolver.get_all_keys() self.assertEqual(solution[0], 81) self.assertEqual(len(solution[1]), 10)
def solve(): s = solver.Solver() s.game.display() print(print_format_string.format('h3', *s.a_star(game.Heuristic.H3))) print(print_format_string.format('h3s', *s.a_star(game.Heuristic.H3s))) print(print_format_string.format('h2', *s.a_star(game.Heuristic.H2))) print(print_format_string.format('h1', *s.a_star(game.Heuristic.H1))) print( print_format_string.format('iterative deepening', *s.iterative_deepening_search())) print( "depth first Fini: {0}, noeuds traités: {1}, coups à jouer depuis l’état initial: {3}" .format(*s.depth_first_search(max_depth=15))) print( print_format_string.format('breadth first', *s.breadth_first_search()))
def __init__(self, puzzle_str): self.puzzle_str = puzzle_str self.root_window = tkinter.Tk() self.root_window.title("Sudoku") self.label = tkinter.Label(master=self.root_window, text="Unsolved puzzle", width="12", height="1") self.label.pack(side=tkinter.TOP) self.label_state = True self.solve_button = tkinter.Button(master=self.root_window, text="Solve puzzle", fg="red", command=self.solve_puzzle) self.solve_button.pack(side=tkinter.TOP) self.new_puzzle_button = tkinter.Button(master=self.root_window, text="New puzzle", fg="red", command=self.new_puzzle) self.new_puzzle_button.pack(side=tkinter.TOP) self.grid = tkinter.Frame(self.root_window) self.grid.pack(side=tkinter.BOTTOM) self.size = 9 self.table = [[ puzzle_str[i + self.size * j] for i in range(self.size) ] for j in range(self.size)] for row in range(self.size): for col in range(self.size): label = tkinter.Label( self.grid, relief=tkinter.RAISED, # raised border padx=10, # make label wide width=2, height=2, text=self.table[row][col]) # label text # place label in row r and column c label.grid(row=row, column=col) self.sol = solver.Solver(9, 3) self.solved_table = None self.root_window.mainloop()
def test_p1e1_solve(self): "Test Solver object creation with text of part 1 example 1" # 1. Test Solver object creation with text of part 1 example 1 mysolver = solver.Solver(text=from_text(test_donut.EXAMPLES[1])) # 2. Make sure it has the specified values self.assertEqual(mysolver.donut.rows, 37) self.assertEqual(mysolver.donut.cols, 35) self.assertEqual(len(mysolver.portal_paths), 12) self.assertEqual(len(mysolver.graph.edges), 56) # 3. Solve the donut maze mysolver.solve_donut_maze() self.assertEqual(len(mysolver.path), 10) self.assertEqual(mysolver.cost, 58)
def test_p1e0_solve(self): "Test Solver object creation with text of part 1 example 0" # 1. Create Donut Maze solver object from part one example 0 mysolver = solver.Solver(text=from_text(test_donut.EXAMPLES[0])) # 2. Make sure it has the specified values self.assertEqual(mysolver.donut.rows, 19) self.assertEqual(mysolver.donut.cols, 19) self.assertEqual(len(mysolver.portal_paths), 5) self.assertEqual(len(mysolver.graph.edges), 22) # 3. Solve the donut maze mysolver.solve_donut_maze() self.assertEqual(len(mysolver.path), 8) self.assertEqual(mysolver.cost, 23)
def test_p2e3_solve(self): "Test Solver object creation with text of part 2 example 3" # 1. Create Intcode obhect with values mysolver = solver.Solver(text=from_text(test_vault.EXAMPLES_PART2[3]), part2=True) #print(mysolver.key_paths.keys()) # 2. Make sure it has the specified values self.assertEqual(mysolver.vault.rows, 9) self.assertEqual(mysolver.vault.cols, 13) self.assertEqual(len(mysolver.key_paths), 19) # 3. Check methods solution = mysolver.get_all_keys() self.assertEqual(solution[0], 72)
def test_empty_init(self): """Test default Solver object creation""" # 1. Create default Astroids object mysolver = solver.Solver() # 2. Make sure it has the default values self.assertEqual(mysolver.vault.text, None) self.assertEqual(mysolver.vault.origin, None) self.assertEqual(mysolver.vault.origins, None) self.assertEqual(len(mysolver.key_paths), 0) # 3. Check methods solution = mysolver.get_all_keys() self.assertEqual(solution[0], 0) self.assertEqual(solution[1], [solver.ORIGIN_KEY])
def draw_carType_new(self): vv = [26.42, 54.79, 68.36, 70.5, 85.79] fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlabel('v/m^3') ax.set_ylabel('distance/km') ax.set_title('cartype-distance picture') y = [] for v in vv: sol = solver.Solver(car_x=v, car_y=1, car_z=1) res = sol.get_saveDisSto_simpleV_mileageStockCost_Fre( disPrice_coe=5.2 * v / 70.5) y.append(res.total_dis) ax.plot(vv, y, label='car_type') plt.legend() plt.show()
def solve_board(index): board = configure.BOARD_MAP[index] s = solver.Solver(board) time_start = time.time() solution = s.solve() time_finished = time.time() if solution: print 'Solution:' print solution print '\nStates Visited:', s.state_visited_count print '\nTotal Seened:', s.state_count print '\nUnique Seened:', len(s.seen) print '\nTime Cost:', time_finished - time_start g = gui.GUI(solution) g.update() g.win.getMouse()
def part_one(args, input_lines): "Process part one of the puzzle" # 1. Create the donut solver krispy_kreme = solver.Solver(text=input_lines, verbose=args.verbose) # 2. Solve the donut maze krispy_kreme.solve_donut_maze() solution = krispy_kreme.cost if solution is None: print("Your could not solve the maze") else: print("You solved the maze in %d steps" % (solution)) # 3. Return result return solution is not None
def solve(self): board = copy.deepcopy(self.board.grid) puzzle_solver = solver.Solver(board, self.num_row, self.num_col) solutions = puzzle_solver.a_star() print(solutions) self.control_buttons('disabled') moves = [self.move_left, self.move_right, self.move_up, self.move_down] for move in reversed(solutions): moves[move.value]( ) # value defined in the Move Enum class in Solver.py self.update() time.sleep(0.2) self.control_buttons('normal')
def test_is(self): netHandler = nt.NetListHandler() input_data = netHandler.readFile("Test-Schaltung.txt") schaltung = nt.Schaltung(input_data) schaltung.initInzidenzMatritzen() solv = solver.Solver(schaltung) solv.createInzidenzMatrices() solv.startwertEntkopplung(solv.potencialList, 0) i_s = solv.i_s(0) expected_i_s = [23] self.assertAlmostEqual(i_s[0], expected_i_s[0], places=15, msg=None, delta=None)
def testFunction1(self): netHandler = nt.NetListHandler() input_data = netHandler.readFile("Test-Schaltung.txt") schaltung = nt.Schaltung(input_data) schaltung.initInzidenzMatritzen() solv = solver.Solver(schaltung) solv.createInzidenzMatrices() solv.startwertEntkopplung(solv.potencialList, 0) func1 = solv.function1([-90], [0], [-999, -900], 0) expected_func1 = [-1.14] self.assertAlmostEqual(func1[0], expected_func1[0], places=15, msg=None, delta=None)
def testMatrixMc(self): netHandler = nt.NetListHandler() input_data = netHandler.readFile("Test-Schaltung.txt") schaltung = nt.Schaltung(input_data) schaltung.initInzidenzMatritzen() solv = solver.Solver(schaltung) solv.createInzidenzMatrices() solv.startwertEntkopplung(solv.potencialList, 0) mc = solv.matrix_mc([-280], 1) expected_mc = [[2.86]] self.assertAlmostEqual(mc[0][0], expected_mc[0][0], places=15, msg=None, delta=None)
def solvePuzzles(): '''Driver code to demonstrate solver algorithm in solve.py. This will eventually have an interactive GUI. ''' sol = solver.Solver(9, 3) board_obj = board.Board(puzzle) helper.display("ORIGINAL BOARD", board_obj) t_0 = time.time() sol.solve(board_obj) t_1 = time.time() if board_obj.solved: helper.display("SOLVED BOARD IN {} seconds".format(t_1-t_0), board_obj) else: print("no solution to this puzzle")
def main(c, n, o): """:parameter c 解の個数の閾値 :parameter n 問題の個数 :parameter o 出力先パス """ # 問題をリスト ans = list() while True: # 問題生成クラス g = Generator() # 最低基準まで入力 if not g.fill(): continue while True: try: # ソルバークラス s = st.Solver(g.get_str(), c) for c in range(2, 5): # N国同盟 s.remove_by_n_association(s.values, c) # 探索 if not s.brute_force(s.values): raise exception.NonAnswerException else: ans.append(g.get_str()) print(g.get_str()) break except exception.NonAnswerException: break except exception.MultipleAnswerException: # 解が複数ある場合は追加で埋める if g.update(): continue else: break if len(ans) == n: break print(ans) with open("./question/{}.csv".format(o), "a") as f: f.write("\n".join(ans))
def __init__(self): # size of the grid self.size = 16 # number of mines on the grid self.mines = 40 # game clock self.clock = pygame.time.Clock() # screen self.screen = pygame.display.set_mode( (Gui.CANVAS_SIZE + Gui.COMMANDS_BAR_SIZE + 2 * Gui.PADDING, Gui.CANVAS_SIZE + 2 * Gui.PADDING)) # Initialize the mines game self.game = game.Game() self.game.set_size(self.size) self.game.set_mines(self.mines) # Initialize the solver module self.solver = solver.Solver(self.game) # true when the Gui is using the solver module self.solving = False # tile that was last edited by the solver self.lastSolvedTile: (int, int) = (-1, -1) # the last mine tile where the left mouse was down self.last_left_down = (-1, -1) # the last mine tile where the right mouse was down self.last_right_down = (-1, -1) # tile that was pressed when the game was lost self.failed_tile = (-1, -1) # Initialize pygame pygame.init() pygame.display.set_caption("'Mines' made by mattlourenco27 on Github") # Icon made by Creaticca Creative Agency from www.flaticon.com icon = pygame.image.load("./assets/sprites/icon.png") pygame.display.set_icon(icon)