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)
Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
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 :]
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))