Day 6: Wait for It


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)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ

  • UlrikHD@programming.dev
    link
    fedilink
    arrow-up
    3
    ·
    edit-2
    11 months ago

    A nice change of pace from the previous puzzles, more maths and less parsing

    Python
    import math
    import re
    
    
    def create_table(filename: str) -> list[tuple[int, int]]:
        with open('day6.txt', 'r', encoding='utf-8') as file:
            times: list[str] = re.findall(r'\d+', file.readline())
            distances: list[str] = re.findall(r'\d+', file.readline())
        table: list[tuple[int, int]] = []
        for t, d in zip(times, distances):
            table.append((int(t), int(d)))
        return table
    
    
    def get_possible_times_num(table_entry: tuple[int, int]) -> int:
        t, d = table_entry
        l_border: int = math.ceil(0.5 * (t - math.sqrt(t**2 -4 * d)) + 0.0000000000001)  # Add small num to ensure you round up on whole numbers
        r_border: int = math.floor(0.5*(math.sqrt(t**2 - 4 * d) + t) - 0.0000000000001)  # Subtract small num to ensure you round down on whole numbers
        return r_border - l_border + 1
    
    
    def puzzle1() -> int:
        table: list[tuple[int, int]] = create_table('day6.txt')
        possibilities: int = 1
        for e in table:
            possibilities *= get_possible_times_num(e)
        return possibilities
    
    
    def create_table_2(filename: str) -> tuple[int, int]:
        with open('day6.txt', 'r', encoding='utf-8') as file:
            t: str = re.search(r'\d+', file.readline().replace(' ', '')).group(0)
            d: str = re.search(r'\d+', file.readline().replace(' ', '')).group(0)
        return int(t), int(d)
    
    
    def puzzle2() -> int:
        t, d = create_table_2('day6.txt')
        return get_possible_times_num((t, d))
    
    
    if __name__ == '__main__':
        print(puzzle1())
        print(puzzle2())