예제 #1
0
def bfs(start, flag):
    expanded = 0
    cost = 0
    moveCount = 0

    llist = LinkedList()
    b = puzz.EightPuzzleBoard(start)
    f = pdqpq.PriorityQueue()

    root = Node(b, "start", None)
    f.add(root)
    fCount = 1
    explored = []

    if complete(root.val):
        cost = 0
        print("start", root.val)
        print("Cost:", cost)
        print("Nodes in Frontier:", fCount)
        print("Nodes Expanded:", expanded)
        return 1

    while not f.empty() and expanded < 100000:
        currNode = f.pop()

        while currNode is None:
            currNode = f.pop()

        dic = expand(currNode.val)
        expanded = expanded + 1
        explored.append(currNode)

        if llist.root is None:
            llist.root = currNode

        for i in dic:
            child = dic[i]
            move = i
            childNode = Node(child, move, currNode)

            # compare currNode.val to childNode.val and determine which tile is swapped
            if childNode not in f and childNode not in explored:
                if complete(childNode.val):
                    NodeChild = childNode
                    while NodeChild.parent is not None:
                        tile = movedTile(NodeChild, NodeChild.parent)
                        if flag == "--noweight":
                            tile = 1
                        cost = cost + pow(tile, 2)
                        NodeChild = NodeChild.parent
                    node = childNode
                    metrics(node, childNode, moveCount, cost, fCount, expanded)

                    return 1
                f.add(childNode)
                fCount = fCount + 1
    print("100,000 nodes expanded, please try another start state.")
    print("Nodes in Frontier:", fCount)
    print("Nodes Expanded:", expanded)
    return -1
예제 #2
0
def h(node, flag):
    heuristic = 0
    goal = puzz.EightPuzzleBoard('012345678')
    puz = puzz.EightPuzzleBoard(str(node.val))

    for i in range(1, 9):
        goalCoord = goal.find(str(i))
        goalX = goalCoord[0]
        goalY = goalCoord[1]

        childCoord = puz.find(str(i))
        childX = childCoord[0]
        childY = childCoord[1]

        mX = abs(goalX - childX)
        mY = abs(goalY - childY)
        m = mX + mY
        if flag is None:
            heuristic = heuristic + m * pow(i, 2)
        else:
            heuristic = heuristic + m

    return heuristic
def search(search_algo, heuristic ,initial_state,final_state):
    exploredcount =0 
    frontiercount=0 
    puzz_board= puzz.EightPuzzleBoard(initial_state)
    frontier = []
    frontier.append(puzz_board)
    frontiercount+=1
    explored =[]

    while (len(frontier)>0 and len(explored)<100000 ):

        node = get_next_node(search_algo,frontier,explored,heuristic, final_state)

        explored.append(node)
        exploredcount+=1

        if (node._board==final_state):            
            return solution(explored, frontiercount,exploredcount)
       
        children =node.successors().values()   
        children=list(filter(None, children)) 
        for n in children:
            flag =0 
            if (type(n)==None):
                flag=1
            for i in frontier :
                if (n==i):
                    #print(type(i))
                    #print("same")
                    flag=1
            for i in explored:
                if (n==i):
                    #print("same")
                    flag=1        
          
            if flag==0:
                #print("added")
                #print(n._board)
                frontier.append(n)   
                frontiercount+=1  
    return "No solution found"
예제 #4
0
import sys
import puzz
import pdqpq

MAX_SEARCH_ITERS = 100000
GOAL_STATE = puzz.EightPuzzleBoard("012345678")


def is_not_empty(list_of_states):
    return len(list_of_states)


def bfs(start_state, results):
    frontier = pdqpq.PriorityQueue()
    explored = set()
    parent = {}
    count = 0
    frontier.add(start_state, count)
    count += 1
    parent[start_state] = ("start", None)

    if start_state == GOAL_STATE:
        results['path'].insert(0, (parent[start_state][0], start_state))
        results['frontier_count'] = count
        results['expanded_count'] = len(explored)
        return results

    while is_not_empty(frontier):
        curr_state = frontier.pop()
        #error checking to be done for pop
        explored.add(curr_state)
예제 #5
0
    return GenericHeuristic(init, goal, H)


def ACount(init, goal):
    def H(c, a, b):
        return c + MissTile(a, b)

    return GenericHeuristic(init, goal, H)


if __name__ == '__main__':
    method = sys.argv[1]
    start = sys.argv[2]
    end = sys.argv[3]
    i = puzz.EightPuzzleBoard(start)
    g = puzz.EightPuzzleBoard(end)
    if method == 'bfs':
        sol = BFS(i, g)
    elif method == 'ucost':
        sol = Uniform(i, g)
    elif method == 'greedy-manhat':
        sol = GreedyManhat(i, g)
    elif method == 'greedy-count':
        sol = GreedyCount(i, g)
    elif method == 'astar-manhat':
        sol = AManhat(i, g)
    elif method == 'astar-count':
        sol = ACount(i, g)
    if sol[0] is None:
        print('No solution')
예제 #6
0
def complete(state):
    if state == puzz.EightPuzzleBoard('012345678'):
        return True
    else:
        return False
예제 #7
0
def astar(start, flag):
    expanded = 0
    cost = 0
    moveCount = 0
    explored = []

    llist = LinkedList()
    b = puzz.EightPuzzleBoard(start)
    f = pdqpq.PriorityQueue()

    root = Node(b, "start", None)
    f.add(root, 0)
    fCount = 1

    if complete(root.val):
        cost = 0
        print("start", root.val)
        print("Cost:", cost)
        print("Nodes in Frontier:", fCount)
        print("Nodes Expanded:", expanded)
        return 1

    while not f.empty() and expanded < 100000:
        currNode = f.pop()
        explored.append(currNode)

        while currNode is None:
            currNode = f.pop()

        dic = expand(currNode.val)
        expanded = expanded + 1

        if llist.root is None:
            llist.root = currNode

        for i in dic:
            path = 0
            child = dic[i]
            move = i
            childNode = Node(child, move, currNode)
            tile = movedTile(currNode, childNode)
            if flag == "--noweight":
                tile = 1
            c = moveCost(tile)
            heuristic = h(childNode, flag)
            childNode.pathCost = c + childNode.parent.pathCost
            if not f.__contains__(childNode) and childNode not in explored:
                # print(heuristic)
                f.add(childNode, heuristic + childNode.pathCost)
                fCount = fCount + 1
            elif f.__contains__(childNode):
                if f.get(childNode) > childNode.pathCost + heuristic:
                    f.add(childNode, childNode.pathCost + heuristic)
            if complete(childNode.val):
                NodeChild = childNode
                while NodeChild.parent is not None:
                    tile = movedTile(NodeChild, NodeChild.parent)
                    if flag == "--noweight":
                        tile = 1
                    cost = cost + pow(tile, 2)
                    NodeChild = NodeChild.parent
                node = childNode
                metrics(node, childNode, moveCount, cost, fCount, expanded)

                return 1
    print("100,000 nodes expanded, please try another start state.")
    print("Nodes in Frontier:", fCount)
    print("Nodes Expanded:", expanded)
    return -1
예제 #8
0
def greedy(start, flag):
    expanded = 0
    cost = 0
    moveCount = 0
    explored = []
    solution = []

    llist = LinkedList()
    b = puzz.EightPuzzleBoard(start)
    f = pdqpq.PriorityQueue()

    root = Node(b, "start", None)
    f.add(root)
    fCount = 1

    if complete(root.val):
        cost = 0
        print("start", root.val)
        print("Cost:", cost)
        print("Nodes in Frontier:", fCount)
        print("Nodes Expanded:", expanded)
        return 1

    while not f.empty() and expanded < 100000:
        currNode = f.pop()
        solution.append(currNode)
        # print(currNode)
        explored.append(currNode)

        while currNode is None:
            currNode = f.pop()
        if complete(currNode.val):
            NodeChild = currNode
            while NodeChild.parent is not None:
                tile = movedTile(NodeChild, NodeChild.parent)
                if flag == "--noweight":
                    tile = 1
                cost = cost + pow(tile, 2)
                NodeChild = NodeChild.parent
            NodeChild = childNode
            metrics(NodeChild, childNode, moveCount, cost, fCount, expanded)
            # for i in range(len(solution)):
            #     print(str(i+1), solution[i].move, solution[i].val)
            # print("Cost:", cost)
            # print("Nodes in Frontier:", fCount)
            # print("Nodes Expanded:", expanded)
            return 1
        dic = expand(currNode.val)
        expanded = expanded + 1

        if llist.root is None:
            llist.root = currNode
        childDict = []
        for i in dic:
            child = dic[i]
            move = i
            childNode = Node(child, move, currNode)
            if not f.__contains__(childNode) and childNode not in explored:

                # tile = movedTile(currNode, childNode)
                # cost = cost + moveCost(tile)
                f.add(childNode, h(childNode, flag))
                fCount = fCount + 1
                # print(childNode.val)
            # print(childNode)
            # print(childNode.val, h(childNode))
        #     childDict.append((childNode, h(childNode, flag)))
        #     lowest = h(childNode, flag)
        #     val = childNode
        # # print(childDict[2][0].val, childDict[1])
        #
        # # print(childDict)
        # for i in childDict:
        #     if i[1] < lowest:
        #         val = i[0]
        #         # print(val)
        #         lowest = i[1]
        # tile = movedTile(currNode, val)
        # cost = cost + moveCost(tile)
        # if not f.__contains__(val) and val not in explored:
        #     # print(val.val)
        #     f.add(val)
        #     fCount = fCount + 1
        #     solution.append(val)

    print("100,000 nodes expanded, please try another start state.")
    print("Nodes in Frontier:", fCount)
    print("Nodes Expanded:", expanded)
    return -1
예제 #9
0
                    if flag == "--noweight":
                        tile = 1
                    cost = cost + pow(tile, 2)
                    NodeChild = NodeChild.parent
                node = childNode
                metrics(node, childNode, moveCount, cost, fCount, expanded)

                return 1
    print("100,000 nodes expanded, please try another start state.")
    print("Nodes in Frontier:", fCount)
    print("Nodes Expanded:", expanded)
    return -1


if __name__ == '__main__':
    goal = puzz.EightPuzzleBoard('012345678')
    arr = []
    generate(goal, 9, arr)

    search = sys.argv[1]  # stores algorithm name in easy to read variable
    start = sys.argv[2]  # stores start state in easy to read variable
    if len(sys.argv) < 4:  # checks length of argv array
        flag = None  # if < 3 we know --noweight flag was NOT entered
    else:
        flag = sys.argv[3]  # else we can pass on the flag

    if flag is not None and flag != "--noweight":
        print("Please try again with a valid flag.")
        quit()

    if search == 'bfs':
예제 #10
0
import sys
import pdqpq
import puzz
import solver

puzzle1 = puzz.EightPuzzleBoard("012345678")
node1 = solver.Node(puzzle1, None, None, None)
puzzle2 = puzz.EightPuzzleBoard("012345678")
node2 = solver.Node(puzzle1, None, None, None)

f = pdqpq.PriorityQueue()
f.add(node1, 0)
f.add(node2, 1)
print(type(node1))
print(node1)
print(node2)
print(type(puzzle1))
print(puzzle1)
print(puzzle2)
print(f.__len__())