this post was submitted on 08 Dec 2023
21 points (92.0% liked)

Advent Of Code

770 readers
75 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2023

Solution Threads

M T W T F S S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

Day 8: Haunted Wasteland

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

you are viewing a single comment's thread
view the rest of the comments
[โ€“] pnutzh4x0r@lemmy.ndlug.org 2 points 11 months ago* (last edited 11 months ago)

Language: Python

Part 1

First part was very straight-forward: read the input in and simulate the navigation. Taking advantage of itertools.cycle made cycling through the instructions very easy :]

Network = dict[str, dict[str, str]]

def read_instructions(stream=sys.stdin) -> Iterator[str]:
    return itertools.cycle(stream.readline().strip())

def read_network(stream=sys.stdin) -> Network:
    network = defaultdict(dict)

    for line in map(str.strip, stream):
        if not line:
            continue

        source, target_l, target_r = re.findall('[A-Z]{3}', line)
        network[source] = {
            'L': target_l,
            'R': target_r,
        }

    return network

def navigate(instructions: Iterator[str], network: Network) -> int:
    count  = 0
    source = 'AAA'
    target = 'ZZZ'

    while source != target:
        source = network[source][next(instructions)]
        count += 1

    return count

def main(stream=sys.stdin) -> None:
    instructions = read_instructions(stream)
    network      = read_network(stream)
    print(navigate(instructions, network))

Part 2

The second part was also straight-forward: locate the ghosts, and then navigate from each ghost until you hit an element that ends with a 'Z'. The trick to avoid brute-forcing is to realize that the ghosts will cycle (ie. repeat the same paths) if they all don't land on an element that ends with a 'Z' at the same time. To solve the problem, you just ened to calculate the steps for each ghost to reach an endpoint and then compute the lowest common multiple of those counts. Fortunately, Python has math.lcm, so not much code was needed!

def navigate(instructions: Iterator[str], network: Network, element: str) -> int:
    count = 0

    while not element.endswith('Z'):
        element = network[element][next(instructions)]
        count += 1

    return count

def locate_ghosts(network: Network) -> list[str]:
    return [element for element in network if element.endswith('A')]

def main(stream=sys.stdin) -> None:
    instructions = read_instructions(stream)
    network      = read_network(stream)
    ghosts       = locate_ghosts(network)
    counts       = [navigate(cycle(instructions), network, ghost) for ghost in ghosts]
    print(math.lcm(*counts))

GitHub Repo