如何在地图中追踪步骤,代码降临 ay 6

wufei123 2025-01-05 阅读:4 评论:0
advent of code 2024: day 6 - guard patrol optimization I'm a bit behind on my Advent of Code challenges this year due to...

advent of code 2024: day 6 - guard patrol optimization

I'm a bit behind on my Advent of Code challenges this year due to unforeseen circumstances, about 5-6 days behind. However, I'm determined to complete the puzzles! Today, let's tackle puzzle six.

如何在地图中追踪步骤,代码降临 ay 6

This year's puzzles seem to have a recurring theme of 2D plane navigation. Today, we're tracking the movements of a guard with a clear, deterministic movement logic: the guard moves in a straight line, turning right when encountering an obstacle.

Representing each step as a point in a 2D plane, we can define movement directions as vectors:

left = (1, 0)
right = (-1, 0)
up = (0, -1)
down = (0, 1)

A rotation matrix representing a right turn is derived as follows:

如何在地图中追踪步骤,代码降临 ay 6

Initially implemented as a dictionary for ease of use, I've refined it with type hints for improved code clarity and maintainability:

class Rotation:
    c0r0: int
    c1r0: int
    c0r1: int
    c1r1: int

@dataclass(frozen=True)
class RotateRight(Rotation):
    c0r0: int = 0
    c1r0: int = 1
    c0r1: int = -1
    c1r1: int = 0

Next, we need classes to represent position, movement, and their manipulation:

from __future__ import annotations
from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: int
    y: int

    def __add__(self, direction: Direction) -> Point:
        return Point(self.x + direction.x, self.y + direction.y)

@dataclass
class Direction:
    x: int
    y: int

    def __mul__(self, rotation: Rotation) -> Direction:
        return Direction(
            self.x * rotation.c0r0 + self.y * rotation.c0r1,
            self.x * rotation.c1r0 + self.y * rotation.c1r1,
        )

The __add__ and __mul__ dunder methods allow for intuitive arithmetic operations on Point and Direction objects. Type hinting ensures code correctness.

Finally, the input model:

from enum import Enum

class Symbol(Enum):
    GUARD = "^"
    OBSTRUCTION = "#"

@dataclass
class Space:
    pass

@dataclass
class Guard:
    pass

@dataclass
class Obstruction:
    pass

@dataclass
class Board:
    tiles: dict[Point, Space | Guard | Obstruction]
    width: int
    height: int

Symbol is a standard enum, Space, Guard, and Obstruction are self-explanatory, and Board represents the map. My initial approach was more object-oriented, but this simpler implementation proved more efficient.

Input parsing:

def finder(board: tuple[str, ...], symbol: Symbol) -> generator[Point, None, None]:
    return (
        Point(x, y)
        for y, row in enumerate(board)
        for x, item in enumerate(tuple(row))
        if item == symbol.value
    )

def parse(input: str) -> tuple[Board, Point]:
    rows = tuple(input.strip().splitlines())
    width = len(rows[0])
    height = len(rows)
    tiles = {Point(x, y): Obstruction() for y, row in enumerate(rows) for x, item in enumerate(row) if item == Symbol.OBSTRUCTION.value}
    return Board(tiles, width, height), next(finder(rows, Symbol.GUARD))

The guard's position is a Point object. finder scans for symbols.

Part 1: Calculating the number of unique tiles visited by the guard.

def check_is_passable(board: Board, point: Point) -> bool:
    return not isinstance(board.tiles.get(point, Space()), Obstruction)

def guard_rotate(direction: Direction, rotation: Rotation) -> Direction:
    return direction * rotation

def guard_move(
    board: Board, guard: Point, direction: Direction, rotation: Rotation
) -> tuple[Direction, Point]:
    destination = guard + direction
    if check_is_passable(board, destination):
        return direction, destination
    else:
        return guard_rotate(direction, rotation), guard

def get_visited_tiles(
    board: Board,
    guard: Point,
    rotation: Rotation,
    direction: Direction = Direction(0, -1), # Default direction: up
) -> dict[Point, bool]:
    tiles = {guard: True}
    while True: #check_is_in_board(board, guard):  Removed board boundary check for simplification.  Assume board is large enough.
        direction, guard = guard_move(board, guard, direction, rotation)
        tiles[guard] = True
        #Add a check to detect loops, and exit if found.  This prevents infinite loops.  (Implementation omitted for brevity)


    return tiles

def part1(input: str) -> int:
    board, guard = parse(input)
    return len(get_visited_tiles(board, guard, RotateRight()))

Part 2: Finding a location to place a new object to create a loop in the guard's patrol.

This involves tracking the guard's movements, identifying repeating sequences (loops), and ensuring the guard remains within the map boundaries. (Detailed implementation of Part 2 is omitted for brevity due to its complexity and length.) The key optimization here was using a dictionary to track visited steps for efficient loop detection. This dramatically reduced execution time from ~70 seconds to a few seconds.

My job search continues (#opentowork). I hope for better results next year. More updates next week.

以上就是如何在地图中追踪步骤,代码降临 ay 6的详细内容,更多请关注知识资源分享宝库其它相关文章!

版权声明

本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com

分享:

扫一扫在手机阅读、分享本文

发表评论
热门文章
  • 华为 Mate 70 性能重回第一梯队 iPhone 16 最后一块遮羞布被掀

    华为 Mate 70 性能重回第一梯队 iPhone 16 最后一块遮羞布被掀
    华为 mate 70 或将首发麒麟新款处理器,并将此前有博主爆料其性能跑分将突破110万,这意味着 mate 70 性能将重新夺回第一梯队。也因此,苹果 iphone 16 唯一能有一战之力的性能,也要被 mate 70 拉近不少了。 据悉,华为 Mate 70 性能会大幅提升,并且销量相比 Mate 60 预计增长40% - 50%,且备货充足。如果 iPhone 16 发售日期与 Mate 70 重合,销量很可能被瞬间抢购。 不过,iPhone 16 还有一个阵地暂时难...
  • 酷凛 ID-COOLING 推出霜界 240/360 一体水冷散热器,239/279 元

    酷凛 ID-COOLING 推出霜界 240/360 一体水冷散热器,239/279 元
    本站 5 月 16 日消息,酷凛 id-cooling 近日推出霜界 240/360 一体式水冷散热器,采用黑色无光低调设计,分别定价 239/279 元。 本站整理霜界 240/360 散热器规格如下: 酷凛宣称这两款水冷散热器搭载“自研新 V7 水泵”,采用三相六极马达和改进的铜底方案,缩短了水流路径,相较上代水泵进一步提升解热能力。 霜界 240/360 散热器的水泵为定速 2800 RPM 设计,噪声 28db (A)。 两款一体式水冷散热器采用 27mm 厚冷排,...
  • 惠普新款战 99 笔记本 5 月 20 日开售:酷睿 Ultra / 锐龙 8040,4999 元起

    惠普新款战 99 笔记本 5 月 20 日开售:酷睿 Ultra / 锐龙 8040,4999 元起
    本站 5 月 14 日消息,继上线官网后,新款惠普战 99 商用笔记本现已上架,搭载酷睿 ultra / 锐龙 8040处理器,最高可选英伟达rtx 3000 ada 独立显卡,售价 4999 元起。 战 99 锐龙版 R7-8845HS / 16GB / 1TB:4999 元 R7-8845HS / 32GB / 1TB:5299 元 R7-8845HS / RTX 4050 / 32GB / 1TB:7299 元 R7 Pro-8845HS / RTX 2000 Ada...
  • Nginx服务器的HTTP/2协议支持和性能提升技巧介绍

    Nginx服务器的HTTP/2协议支持和性能提升技巧介绍
    Nginx服务器的HTTP/2协议支持和性能提升技巧介绍 引言:随着互联网的快速发展,人们对网站速度的要求越来越高。为了提供更快的网站响应速度和更好的用户体验,Nginx服务器的HTTP/2协议支持和性能提升技巧变得至关重要。本文将介绍如何配置Nginx服务器以支持HTTP/2协议,并提供一些性能提升的技巧。 一、HTTP/2协议简介:HTTP/2协议是HTTP协议的下一代标准,它在传输层使用二进制格式进行数据传输,相比之前的HTTP1.x协议,HTTP/2协议具有更低的延...
  • 两个表格切换的快捷键是什么

    两个表格切换的快捷键是什么
    两个表格切换的快捷键是“ctrl+pageup”和“ctrl+pagedown”,按键盘上的“ctrl+pageup”键是向右切换表格,按“ctrl+pagedown”键是向左切换表格。 本教程操作环境:windows7系统、Microsoft Office Excel2010版、Dell G3电脑。 两个工作表之间切换是Ctrl+Tab,两个工作簿之间切换是Ctrl+PageUP和Ctrl+PageDown。 打开Excel表格,打开几个工作簿。 按键盘上的Ctrl+P...