def choose_search_algorithm(pegboard):
    while True:

        print("Choose Search Algorithm \n\n"
              "1. Breadth-First Search\n"
              "2. Depth-First Search\n"
              "3. Greedy Best-First Search\n"
              "4. A* Search\n")

        choice = int(input("Enter Choice: "))

        # Call search algorithm function that user selects.
        if choice == 1:
            bfs.breadth_first_search(pegboard)
            break
        elif choice == 2:
            dfs.depth_first_search_start(pegboard)
            break
        elif choice == 3:
            gbf.greedy_best_start(pegboard)
            break
        elif choice == 4:
            a_star.a_star_start(pegboard)
            break
        else:
            print("Invalid option")
Example #2
0
 def test_capped_bfs(self):
     """test bfs with a depth limitation"""
     out = []
     bfs.breadth_first_search(dict_list_adaptor(self.graph), "A", max_depth_bfs_visitor(out, 2))
     distance_map = dict(out)
     self.assertEqual(distance_map["A"], 0)
     self.assertEquals(False, distance_map.has_key("E"))
Example #3
0
 def test_basic_bfs(self):
     """test the basic bfs case"""
     out = []
     bfs.breadth_first_search(dict_list_adaptor(self.graph), "A", test_bfs_adaptor(out))
     distance_map = dict(out)
     self.assertEqual(distance_map["A"], 0)
     self.assertEqual(distance_map["B"], 1)
     self.assertEqual(distance_map["C"], 1)
     self.assertEqual(distance_map["F"], 2)
     self.assertEqual(distance_map["D"], 2)
     self.assertEqual(distance_map["E"], 3)
Example #4
0
    def test_bfs_single_hop(self):
        g1 = Graph("""
            a -> b
            b -> c
            a -> d
            e -> d
            """)

        result = bfs.breadth_first_search(g1, "b", "c")
        self.assertEqual(result, True)

        result = bfs.breadth_first_search(g1, "a", "e")
        self.assertEqual(result, False)
def solve():
    initial_state = get_initial_state()
    if not initial_state:
        tkinter.messagebox.showerror('错误', '非法初始状态')
        return
    goal_state = get_goal_state()
    if not goal_state:
        tkinter.messagebox.showerror('错误', '非法目标状态')
        return
    choice = var.get()
    path = []
    if choice == 1:
        path = bfs.breadth_first_search(initial_state, goal_state)
    elif choice == 2:
        path = dfs.depth_first_search(initial_state, goal_state)
    elif choice == 3:
        path = iddfs.iterative_deepening_dfs(initial_state, goal_state)
    elif choice == 4:
        path = best_first.best_first_search(initial_state, goal_state)
    elif choice == 5:
        path = bidirectional.bidirectional_search(initial_state, goal_state)
    elif choice == 6:
        path = a_star.a_star_search(initial_state, goal_state)
    elif choice == 7:
        path = ida_star.iterative_deepening_a_star(initial_state, goal_state)
    output.delete(1.0, END)
    output.insert(1.0, auxiliary.path_to_str(path))
Example #6
0
    def test_moves_count(self):
        root_node = Node(None, "185432_67", 0, None)

        final_node, monitor = breadth_first_search(root_node)

        final_node_moves = final_node.get_path_moves()

        expected_moves_count = 20

        self.assertEqual(expected_moves_count, len(final_node_moves),
                         "incorrect expected moves count")
def run_bfs_algorithm(arguments: Arguments):
    root_node = Node(  # <-- Estado Inicial:
        None,  # <-- a) State
        arguments.initial_state,  # <-- b) Action
        0,  # <-- c) Cost
        None  # <-- d) Predecessor
    )

    final_node, monitor = breadth_first_search(root_node)

    log_results(final_node, monitor)
Example #8
0
    def test_root_is_objective(self):
        root_node = Node(None, "12345678_", 0, None)

        final_node, monitor = breadth_first_search(root_node)
        final_node_moves = final_node.get_path_moves()

        expected_path_moves = []

        expected_expansions = 0

        self.assertEqual(expected_path_moves, final_node_moves,
                         "path is incorrect")
        self.assertEqual(expected_expansions, monitor.expansions,
                         "incorrect expected expansions")
Example #9
0
    def test_two_moves_to_objective(self):
        root_node = Node(None, "123456_78", 0, None)

        final_node, monitor = breadth_first_search(root_node)
        final_node_moves = final_node.get_path_moves()

        expected_path_moves = ['direita', 'direita']

        expected_expansions = 3

        self.assertEqual(expected_path_moves, final_node_moves,
                         "path is incorrect")
        self.assertEqual(expected_expansions, monitor.expansions,
                         "incorrect expected expansions")
Example #10
0
    def test_bfs_multiple_hop(self):
        g1 = Graph("""
            a -> b
            b -> c
            a -> e
            e -> f
            g -> h
            b -> g
            c -> h
            i -> h
            """)

        result = bfs.breadth_first_search(g1, "a", "h")
        self.assertEqual(result, True)

        result = bfs.breadth_first_search(g1, "a", "f")
        self.assertEqual(result, True)

        result = bfs.breadth_first_search(g1, "a", "f")
        self.assertEqual(result, True)

        result = bfs.breadth_first_search(g1, "a", "i")
        self.assertEqual(result, False)
Example #11
0
    def test_unsolvable(self):
        root_node = Node(None, "2_5341687", 0, None)

        final_node, monitor = breadth_first_search(root_node)

        n = 9
        fact = 1

        for i in range(1, n + 1):
            fact = fact * i

        max_expansions = fact / 2

        self.assertFalse(final_node)
        self.assertEqual(max_expansions, monitor.expansions,
                         "incorrect expected expansions")
Example #12
0
    def test_real(self):
        root_node = Node(None, "3456_8172", 0, None)

        final_node, monitor = breadth_first_search(root_node)
        final_node_moves = final_node.get_path_moves()

        expected_path_moves = [
            'esquerda', 'abaixo', 'direita', 'direita', 'acima', 'esquerda',
            'acima', 'esquerda', 'abaixo', 'direita', 'abaixo', 'direita',
            'acima', 'acima', 'esquerda', 'abaixo', 'direita', 'abaixo'
        ]

        expected_expansions = 23313

        self.assertEqual(expected_path_moves, final_node_moves,
                         "path is incorrect")
        self.assertEqual(expected_expansions, monitor.expansions,
                         "incorrect expected expansions")
Example #13
0
    def test_node_counter(self):
        root_node = Node(None, "2_3541687", 0, None)

        final_node, monitor = breadth_first_search(root_node)
        final_node_moves = final_node.get_path_moves()

        expected_path_moves = [
            'esquerda', 'abaixo', 'direita', 'direita', 'acima', 'esquerda',
            'abaixo', 'abaixo', 'esquerda', 'acima', 'acima', 'direita',
            'direita', 'abaixo', 'esquerda', 'abaixo', 'direita', 'acima',
            'esquerda', 'esquerda', 'abaixo', 'direita', 'direita'
        ]

        expected_expansions = 100002

        self.assertEqual(expected_path_moves, final_node_moves,
                         "path is incorrect")
        self.assertEqual(expected_expansions, monitor.expansions,
                         "incorrect expected expansions")
Example #14
0
def decideMoveGood(data):
	graph = board.get_board(data)
	currX = data['you']["body"]["data"][0]['x']
	currY = data['you']["body"]["data"][0]['y']
	startP = (currX, currY)

	checkX = None
	checkY = None
	for i in data['food']['data']:
		smallestX = abs(i['x'] - currX)
		if checkX == None or smallestX > checkX:
			smallestX = i['x']
		smallestY = abs(i['y'] - currY)
		if checkY == None or smallestY > checkY:
			smallestY = i['y']
	goalF = (checkX, checkY)

	path = bfs.breadth_first_search(graph, startP, goalF)
	return directionToGo(path, startP)
Example #15
0
while option != "5":

    if option == "1":
        helper_fn.print_floor(floor)
        print(f"x coordinate of vacuum cleaner: {state.pos_x}")
        print(f"y coordinate of vacuum cleaner: {state.pos_y}")

        app = QApplication(sys.argv)
        ex = Current_State(state, size)
        sys.exit(app.exec_())

    if option == "2":
        helper_fn.print_floor(floor)
        print(f"x coordinate of vacuum cleaner: {state.pos_x}")
        print(f"y coordinate of vacuum cleaner: {state.pos_y}")
        sol_bfs = bfs.breadth_first_search(state, goal_state)

        print(f"This is the solution path: {bfs.sol_path(sol_bfs)}")
        print(f"Path cost : {sol_bfs.path_cost}")

    if option == "3":
        helper_fn.print_floor(floor)
        print(f"x coordinate of vacuum cleaner: {state.pos_x}")
        print(f"y coordinate of vacuum cleaner: {state.pos_y}")
        sol_idfs = iterative_deepening.iterative_deepening_search(
            state, goal_state)

        print(f"This is the solution path: {bfs.sol_path(sol_idfs)}")
        print(f"Path cost : {sol_idfs.path_cost}")

    if option == "4":
Example #16
0
#ID: 2017A7PS0093P

#########################
import helper_fn
import helper_ds
import bfs
import iterative_deepening
import time

size = 3

time_G3_bfs = open("G3_bfs.txt", "w")
for i in range(17):

    goal_floor = helper_fn.dirt_generator(size, 0)
    helper_fn.print_floor(goal_floor)
    goal_state = helper_ds.State(goal_floor, 0, 0)

    new_floor = helper_fn.dirt_generator(size, 0.1)
    new_state = helper_ds.State(new_floor, 0, 0)
    start_time = time.time()

    solution = bfs.breadth_first_search(new_state, goal_state)

    time_taken = time.time() - start_time
    print(f"Total time taken: {time_taken}")
    time_G3_bfs.write(f"Total time taken: {time_taken}")
    size = size + 1

time_G3_bfs.close()
Example #17
0
 def test_terminating_return_value(self):
     out = []
     terminator = bfs.breadth_first_search(dict_list_adaptor(self.graph), "A", max_depth_bfs_visitor(out, 2))
     self.assertEqual(terminator, "E")
Example #18
0
from time import time
from bfs import breadth_first_search
from puzzle import Puzzle

kondisi=[[1, 8, 2,
        0, 4, 3,
        7, 6, 5]]

Puzzle.num_of_instances=0
t0=time()
bfs=breadth_first_search(kondisi[0])
t1=time()-t0
print('Route:', bfs)
print('Expanded Node:',Puzzle.num_of_instances)
print('Running Time:',t1)
Example #19
0
if __name__ == '__main__':
    bfs.NotesNum = 0

    initState = [[0, 0, 0, 1, 0, 0, 0, 7, 0], [7, 3, 0, 0, 9, 0, 0, 0, 0],
                 [2, 0, 0, 0, 6, 4, 0, 3, 0], [0, 0, 6, 0, 0, 1, 0, 4, 0],
                 [0, 0, 1, 3, 0, 0, 0, 2, 6], [0, 0, 0, 2, 0, 0, 8, 0, 0],
                 [0, 6, 8, 4, 0, 0, 9, 0, 0], [3, 0, 0, 9, 0, 0, 0, 0, 0],
                 [1, 0, 0, 0, 0, 0, 0, 0, 0]]

    print(colored("\nSudoku that will be solved", "blue"))
    displaytoscreen(initState)

    problem = bfs.Problem(initState)
    starttime = time.time()
    bfs.result = bfs.breadth_first_search(problem)
    endtime = time.time()

    if (bfs.result == None):
        print(colored("Sudoku can not be solved", "red"))
    else:
        print(colored("Congratulations! Sudoku solved", "blue"))

        displaytoscreen(bfs.result.state)

    print(
        colored(
            "\nThe algorithm took {0:0.3f} seconds to find solution".format(
                endtime - starttime), "blue"))

    print("The total child notes searched : ", colored(bfs.NotesNum, "green"))
def build_amazon_graph(keyword, depth):
    return bfs.breadth_first_search(amazon_similarity_adaptor(), get_nearest_asin(keyword), pygraphlib_builder_visitor(pygraph.UGraph(), depth))
# lab4_checkpoint.py
# CS 1 Lab Assignment #4 checkpoint by THC.
# Creates a dictionary of Vertex objects based on reading in a file.
# Writes out a string for each Vertex object to a file.

from load_graph import load_graph
from bfs import breadth_first_search

vertex_dict = load_graph("dartmouth_graph.txt")

out_file = open("vertices.txt", "w")
for vertex in vertex_dict:
    out_file.write(str(vertex_dict[vertex]) + "\n")
out_file.close()

start = vertex_dict["Rocky"]
goal = vertex_dict["AXA"]
print breadth_first_search(start, goal)
Example #22
0
        "B": ["A", "D", "E"],
        "C": ["A", "F"],
        "D": ["B", "D"],
        "E": ["B", "F"],
        "F": ["C", "E", "G"],
        "G": ["F"],
    }

    # Perform Depth-First Search using stacks
    print("DFS: ", depth_first_search(graph, "A", "G"))

    # Perform Depth-First Search using recursive function
    print("DFS(Recursive):", depth_first_search_recursive(graph, "A", "G", set()))

    # Perform Breadth-First Search to find a path between A to G
    print("BFS:", breadth_first_search(graph, "A", "G"))

    graph = {
        "A": ["D"],
        "B": ["D"],
        "C": ["A", "B"],
        "D": ["G", "H"],
        "E": ["A", "D", "F"],
        "F": ["K", "J"],
        "G": ["I"],
        "H": ["I", "J"],
        "I": ["L"],
        "J": ["M", "L"],
        "K": ["J"],
        "L": [],
        "M": [],
Example #23
0
"""

is_goal = lambda x: x == 'HOH'

def successors(available_replacements, invert=False):
	replacements = parse_replacements(available_replacements, invert=invert)
	max_replacements_key_length = max([len(x) for x in replacements.keys()])

	def result(starting_molocule):
		for chunk, i, j in chunks(starting_molocule, max_replacements_key_length):
			for replacement in replacements[chunk]:
				yield starting_molocule[:i] + replacement + starting_molocule[j:]

	return result

assert len(breadth_first_search('e', is_goal, successors(example_replacements))) == 3

assert len(breadth_first_search('e', lambda x: x=='HOHOHO', successors(example_replacements))) == 6

def heuristic_better_shorten(successor, path, initial_state):
	last_element_in_path = len(path) > 0 and path[len(path) - 1]
	if not last_element_in_path:
		return len(successor) < len(initial_state)
	else:
		return len(successor) < len(last_element_in_path)

def pick_next_strategy(frontier):
	longest_path = sorted(frontier, key=lambda x: -len(x[1]))
	candidate = longest_path[0]
	frontier.remove(candidate)
	return candidate