def find(self, debugger: Debugger = Debugger(enabled=False)) -> Paths:
        def reporting_format(_: Debugger, message: str) -> str:
            return (
                f"{message} ({len(paths)} found, {len(seen)} seen, "
                f"{len(stack)} in stack)"
            )

        paths = []
        stack: List[CaveFinderStateT] = [self.get_state_class().make_initial()]
        seen = {stack[0]}
        with debugger.adding_extra_report_format(reporting_format):
            debugger.default_report("Looking...")
            while debugger.step_if(stack):
                debugger.default_report_if("Looking...")
                state = stack.pop(0)
                for next_state in state.get_next_states(self.system.graph):
                    if next_state in seen:
                        continue
                    seen.add(next_state)
                    if next_state.is_terminal:
                        paths.append(next_state.path)
                        continue
                    stack.append(next_state)
            debugger.default_report("Finished looking")

        return paths
    def __mul__(
            self,
            count: int,
            debugger: Debugger = Debugger(enabled=False),
    ) -> "ModuloShuffle":
        cls = type(self)
        if count < 0:
            raise Exception(f"Cannot calculate negative count shuffle")

        # noinspection PyArgumentList
        total = cls(
            factor=1,
            offset=0,
            size=self.size,
        )
        power_shuffle = self
        power = 1
        remaining_count = count
        debugger.default_report(
            f"Remaining {math.ceil(math.log2(remaining_count))} rounds "
            f"({remaining_count}, {bin(remaining_count)})")
        while debugger.step_if(remaining_count):
            debugger.default_report_if(
                f"Remaining {math.ceil(math.log2(remaining_count))} rounds "
                f"({remaining_count}, {bin(remaining_count)})")
            if remaining_count % 2:
                total = total + power_shuffle
            remaining_count //= 2
            power *= 2
            power_shuffle = power_shuffle + power_shuffle

        return total
示例#3
0
    def solve(
            self, node_set: 'NodeSetExtended',
            target: Point2D = Point2D.ZERO_POINT,
            debugger: Debugger = Debugger(enabled=False),
    ) -> List['NodeSetExtended']:
        stack = [node_set]
        previous_map: PreviousMap = {node_set: None}
        duplicate_count = 0
        debugger.reset()
        target_position_map = self.get_target_positions(node_set)
        debugger.reset()
        while debugger.step_if(stack):
            current_node_set = stack.pop(0)
            next_states = self.get_next_states(
                current_node_set, target_position_map)
            for next_node_set in next_states:
                if next_node_set in previous_map:
                    duplicate_count += 1
                    continue
                previous_map[next_node_set] = current_node_set
                if next_node_set.position == target:
                    return self.get_solution(next_node_set, previous_map)
                stack.append(next_node_set)

            if debugger.should_report():
                debugger.default_report(
                    f"stack: {len(stack)}, pruned: {duplicate_count}")

        raise Exception(f"Could not find solution")
    def find_minimum_cost_to_organise(
        self, debugger: Debugger = Debugger(enabled=False),
    ) -> int:
        """
        >>> Maze.from_maze_text('''
        ...     #############
        ...     #...........#
        ...     ###B#C#B#D###
        ...       #A#D#C#A#
        ...       #########
        ... ''').find_minimum_cost_to_organise()
        12521
        """
        stack = [(0, 0, self)]
        seen_cost = {self: 0}
        min_cost: Optional[int] = None
        while debugger.step_if(stack):
            move_count, cost, maze = stack.pop(0)
            if seen_cost[maze] < cost:
                continue
            next_move_count = move_count + 1
            next_stack = []
            for move_cost, next_maze in maze.get_next_moves():
                next_cost = cost + move_cost
                if seen_cost.get(next_maze, next_cost + 1) <= next_cost:
                    continue
                if min_cost is not None and min_cost <= next_cost:
                    continue
                next_stack.append((next_move_count, next_cost, next_maze))
            if not next_stack:
                continue
            max_next_finish_count = max(
                next_maze.finish_count
                for _, _, next_maze in next_stack
            )
            for next_move_count, next_cost, next_maze in next_stack:
                if next_maze.finish_count < max_next_finish_count:
                    continue
                if next_maze.finished:
                    min_cost = next_cost
                    continue
                stack.append((next_move_count, next_cost, next_maze))
                seen_cost[next_maze] = next_cost
            if debugger.should_report():
                debugger.default_report(
                    f"{len(stack)} in stack, seen {len(seen_cost)}, "
                    f"last move count is {move_count}, last cost is {cost}, "
                    f"min cost is {min_cost}, last maze is:\n{maze}\n"
                )
        debugger.default_report(
            f"{len(stack)} in stack, seen {len(seen_cost)}, "
            f"min cost is {min_cost}"
        )

        if min_cost is None:
            raise Exception(f"Could not find end state")

        return min_cost
示例#5
0
    def solve(
            self,
            debugger: Debugger = Debugger(enabled=False),
    ) -> "QuantumGameSearch":
        while not debugger.step_if(self.finished):
            self.advance_once()
            debugger.default_report_if(
                f"Done {self.move_count} moves, with "
                f"{len(self.residual_state_counts)} remaining states, "
                f"currently {self.player_1_wins} vs {self.player_2_wins}")

        return self
示例#6
0
    def find_min_mana_necessary(
            self,
            debugger: Debugger = Debugger(enabled=False),
    ) -> int:
        def reporting_format(_: Debugger, message: str) -> str:
            if min_mana_spent is None:
                min_mana_spent_str = "no winner yet"
            else:
                min_mana_spent_str = f"best is {min_mana_spent}"
            return f"{message} ({min_mana_spent_str}, {len(stack)} in stack)"

        with debugger.adding_extra_report_format(reporting_format):
            stack = [deepcopy(self)]
            min_mana_spent = None
            min_mana_game = None
            debugger.default_report_if("Searching for a winning game...")
            while debugger.step_if(stack):
                debugger.default_report_if("Searching for a winning game...")
                game = stack.pop(0)
                if min_mana_spent is not None \
                        and game.player.mana_spent >= min_mana_spent:
                    continue
                next_games = game.get_next_games(debugger)
                for next_game in next_games:
                    if (min_mana_spent is not None
                            and next_game.player.mana_spent >= min_mana_spent):
                        continue
                    if next_game.winner == CharacterEnum.Player:
                        min_mana_spent = next_game.player.mana_spent
                        min_mana_game = next_game
                        debugger.report(f"Better game found: {min_mana_spent}")
                    stack.append(next_game)

            debugger.default_report(f"Finished searching")

        if min_mana_spent is None:
            raise Exception(f"Could not find a winning game")

        options_played_str = ', '.join(
            option.name for option in min_mana_game.options_played
            if isinstance(option, SpellEnum))
        debugger.report(f"Min mana game moves: {options_played_str}")

        return min_mana_spent
    def measure_distances(
            self,
            debugger: Debugger = Debugger(enabled=False),
    ) -> None:
        while debugger.step_if(self.stack):
            should_report = debugger.should_report()
            debugger.default_report_if(
                f"Seen {len(self.distances)}, {len(self.stack)} in stack, "
                f"target risk is {self.distances.get(self.target)}")
            if should_report:
                debugger.report(str(self))
            state = self.stack.pop(0)
            if state.distance > self.distances[state.position]:
                continue

            for next_state in state.get_next_states(self):
                self.visit_state(next_state)
        if debugger.enabled:
            debugger.report(str(self))
示例#8
0
    def apply_extended(
            self,
            state: Optional[StateExtended] = None,
            debugger: Debugger = Debugger(enabled=False),
    ) -> StateExtended:
        """
        >>> def check(instructions_text, state_values=None, program_counter=0):
        ...     _state = InstructionSetExtended\\
        ...         .from_instructions_text(instructions_text)\\
        ...         .apply_extended(StateExtended(
        ...             state_values or {}, program_counter))
        ...     # noinspection PyUnresolvedReferences
        ...     values = {
        ...         name: value
        ...         for name, value in _state.values.items()
        ...         if value
        ...     }
        ...     return values, _state.program_counter
        >>> check(
        ...     "cpy 2 a\\n"
        ...     "tgl a\\n"
        ...     "tgl a\\n"
        ...     "tgl a\\n"
        ...     "cpy 1 a\\n"
        ...     "dec a\\n"
        ...     "dec a\\n"
        ... )
        ({'a': 3}, 7)
        """
        if state is None:
            state = StateExtended()
        state.instructions = list(self.instructions)
        debugger.reset()
        while debugger.step_if(
                0 <= state.program_counter < len(state.instructions)):
            self.step(state)
            if debugger.should_report():
                debugger.default_report(
                    f"values: {state.values}, pc: {state.program_counter}")

        return state
    def find_scanners_positions(
        self,
        debugger: Debugger = Debugger(enabled=False),
    ) -> List[Tuple[BeaconT, ScannerT]]:
        """
        >>> # noinspection PyUnresolvedReferences
        >>> [_position for _position, _ in Scanner2DSet.from_scanners_text('''
        ...     --- scanner 0 ---
        ...     0,2
        ...     4,1
        ...     3,3
        ...
        ...     --- scanner 1 ---
        ...     -1,-1
        ...     -5,0
        ...     -2,1
        ... ''').find_scanners_positions()]
        [Beacon2D(x=0, y=0), Beacon2D(x=5, y=2)]
        """
        if not self.scanners:
            return []

        beacon_class = self.get_beacon_class()
        first_scanner = self.scanners[0]
        positions_and_scanners_by_scanner: Dict[int, Tuple[BeaconT, ScannerT]] \
            = {
                id(first_scanner):
                (beacon_class.get_zero_point(), first_scanner)
            }
        found_scanners = [first_scanner]
        remaining_scanners = self.scanners[1:]
        debugger.default_report(
            f"Looking for {len(self.scanners) - 1} positions, found "
            f"{len(found_scanners) - 1}")
        while remaining_scanners:
            for other_index, other in enumerate(remaining_scanners):
                for found_index, found_scanner \
                        in debugger.step_if(enumerate(found_scanners)):
                    debugger.default_report_if(
                        f"Looking for {len(self.scanners) - 1} positions, "
                        f"found {len(found_scanners) - 1}")
                    found_position, found_reoriented = \
                        positions_and_scanners_by_scanner[id(found_scanner)]
                    position_and_scanner = \
                        found_reoriented.find_other_scanner_position(
                            other, self.min_overlap,
                        )
                    if not position_and_scanner:
                        continue

                    position, reoriented = position_and_scanner
                    position = position.offset(found_position)
                    found_scanners.append(other)
                    positions_and_scanners_by_scanner[id(other)] = \
                        position, reoriented
                    remaining_scanners.remove(other)
                    break
                else:
                    continue

                break
            else:
                raise Exception(f"Could not find any remaining scanner "
                                f"({len(remaining_scanners)} remaining out of "
                                f"{len(self.scanners)})")

        return [
            positions_and_scanners_by_scanner[id(scanner)]
            for scanner in self.scanners
        ]