Day 2: Gift Shop

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

you are viewing a single comment's thread
view the rest of the comments
[โ€“] 2 points 11 months ago

Python

I love it when I can just slap a problem with a regex and be done with it.

import re

from pathlib import Path
from typing import Generator

def parse_input(input: str) -> Generator[range, None, None]:
    for r in input.split(","):
        v = r.split("-")
        yield range(int(v[0]), int(v[1]) + 1)


def solve(input: str, pattern: str) -> int:
    exp = re.compile(pattern)
    return sum(
        map(
            lambda m: int(m.group()),
            filter(
                None,
                map(lambda s: exp.match(s), [n for r in parse_input(input) for n in map(str, r)])
            )
        )
    )


if __name__ == "__main__":
    input = Path("_2025/_2/input").read_text("utf-8")
    print(solve(input, r"^(\d+)\1$"))
    print(solve(input, r"^(\d+)\1+$"))
  • source