Advent of Code 2025 挑战全手写代码 Day 1 - 秘密入口

🎄Advent of Code 2025 挑战全手写代码 Day 1 - 秘密入口


终于等到 AoC 2025 开赛啦!🎉 第一天题目 Secret Entrance 难度简单(一星⭐),主要考察对 循环结构(Circular Buffer) 的理解和模运算的运用。

📖 题目速览

题目地址:adventofcode.com/2025/day/1

我们在北极秘密入口遇到一个保险箱转盘,刻度 0-99,初始位置 50。 输入是一串旋转指令(如 L68, R48)。

  • Part 1 :统计每次旋转结束时 ,指针停在 0 的次数。
  • Part 2 :统计旋转过程中 (包含结束点)指针指向 0 的总次数。

💡 解题思路 (Python 🐍)

  1. 巧用取模 % : 转盘是环形的,Python 的模运算 % 就能搞定
    • 右转:(current + amount) % 100
    • 左转:(current - amount) % 100
    • Python 的 % 能完美处理负数(例如 -1 % 100 = 99),直接省去了繁琐的边界判断,代码瞬间清爽!
python 复制代码
current: int = 50
out: int = 0

for direction, amount in self.sequence:
    match direction:
        case "R":
            current = (current + amount) % 100
        case "L":
            current = (current - amount) % 100

    if not current:
        out += 1
  1. Part 2 的优化陷阱 : 题目提示可能会有像 R1000 这种大旋转。如果一步步模拟(for loop),效率会很低。
    • 数学解法 :使用 divmod(amount, 100)
    • 整圈 :商 (div) 表示转了几整圈,每圈必然经过一次 0。
    • 残余步数 :余数 (mod) 是剩下的位移。只需判断这最后一段位移是否跨越了 0 界限(R 跨越 99->0,L 跨越 0->99)。
python 复制代码
current: int = 50
out: int = 0

for direction, amount in self.sequence:
    div, mod = divmod(amount, 100)
    out += div

    match direction:
        case "R":
            if current + mod >= 100:
                out += 1

            current = (current + mod) % 100
        case "L":
            if current > 0 and mod >= current:
                out += 1

            current = (current - mod) % 100

return out

✨ 代码复盘 最终代码将"计算经过次数"和"更新位置"解耦,逻辑非常清晰。相比于暴力模拟,数学计算法不仅快,而且更能体现算法思维。

完整代码:访问 github

Happy Coding! 冲刺排行榜!🚀

相关推荐
wangruofeng9 小时前
opencodex 解锁 Codex 任意模型,一个本地代理打通 Claude/Kimi/GLM/DeepSeek
llm·github·openai
大模型码小白10 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
麻雀飞吧10 小时前
最新量化学习路径,交易认知和技术实现要并行
人工智能·python
一点一木10 小时前
从60首歌到1个网站:输入你的故事,还你一首歌
前端·github
C^h14 小时前
python函数学习
人工智能·python·机器学习
Fanta丶14 小时前
4.Python set()集合、dict(字典、映射)、 数据容器的通用功能
python
决战灬14 小时前
langgraph之interrupt(理论篇)
人工智能·python·agent
兜客互动15 小时前
2026年AI关键词拓展挖掘软件,高效助力内容创作精准获流
人工智能·python
weixin_5386019715 小时前
智能体测开Day30pytest测试框架
python
MC皮蛋侠客15 小时前
uv 系列(七):CI/CD、Docker 与私有索引——生产级交付
python·ci/cd·docker·uv