pacai.search.random

 1import random
 2import typing
 3
 4import pacai.core.search
 5
 6def random_search(
 7        problem: pacai.core.search.SearchProblem,
 8        heuristic: pacai.core.search.SearchHeuristic,
 9        rng: random.Random,
10        **kwargs: typing.Any) -> pacai.core.search.SearchSolution:
11    """
12    Perform a random (and really stupid) search.
13    Users should strive to implement better searches as soon as possible.
14    """
15
16    actions = []
17    cost = 0.0
18
19    # Start at the start.
20    current_node = problem.get_starting_node()
21
22    # Keep going until we get to the goal.
23    while (not problem.is_goal_node(current_node)):
24        successors = problem.get_successor_nodes(current_node)
25
26        if (len(successors) == 0):
27            raise ValueError("Unable to find solution.")
28
29        # Randomly choose a successor.
30        successor = rng.choice(successors)
31
32        # Move to the next node.
33        current_node = successor.node
34        actions.append(successor.action)
35        cost += successor.cost
36
37    return pacai.core.search.SearchSolution(actions, cost, current_node)