↓ Zum Hauptinhalt springen
  1. Blogs/

Advent of Code - 02 - Fulminating Farmland

Inhaltsverzeichnis
Advent of Code 2026 - Dieser Artikel ist Teil einer Serie.
Teil : Dieser Artikel

“You ride the train to its first stop: a large farm surrounded by fields. The Elves explain that you’re not actually here for anything the farm grows; apparently, this farm also collects thunder from passing storms. This explains the surprisingly rumbly crates being loaded onto the train.”

Teil 1
#

In Teil 1 sollen wir die Distanz für einen Roboter bestimmen. Gegeben ist ein Instructionset aus Farben, welche letztlich für Schrittweiten stehen. Ich muss gestehen, dass ich den Teil schwieriger als den zweiten Teil fand, da ich mich lange zu sehr an dem gegeben Beispiel orierentiert hatte. Dabei stand eigentlich alles im Text.

Naja as user-specific Input bekommt man ein Programm was aus Instruktionen aus dem Instructionset bestehen und gesucht is die Gesamtdistanz des Programms (deines Inputs). Das heißt, dass wir über das Programm iterieren und uns anschauen, welche Distanz die jeweilige Instruktion hat. Da diese nur im Bereich 0 bis 6 liegen kann, lünnen wir das Ganze oberhalb abschneiden. Danach wird die Distanz zur Summe hinzugefügt und weiter geht es nach einem Positionsupdate

 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

FILENAME = "input.txt"
SEQUENCE = "roygbvroygbvroygbvroygbvroygbvroygbvroygbvroygbv"


def readfile(filename: str) -> str:
    with open(filename) as file:
        return "".join(file.read().split())
    return ""


def calculate_distance(order: str, program: str) -> int:
    total: int = 0
    pos: int = 0
    for ch in program:
        try:
            t = order.index(ch)
            d = (t - pos) % 6
            if d == 0:
                d = 6
            total += d
            pos = t
        except ValueError:
            print(f"char {ch} not found.")
            continue

    return total


def partone():
    # test cases (given by task)
    program = ["obbvb", "roygbv", "vbgyor", "vvvvvv"]
    for prog in program:
        dist = calculate_distance(SEQUENCE, prog)
        print(f"{prog} -> total distance: {dist}")
    
    # user specific task
    INPUT = readfile(FILENAME)
    dist = calculate_distance(program[1], INPUT)
    print(f"{INPUT} -> total distance: {dist}")

if __name__ == "__main__
    partone()

Teil 2
#

Im zweiten Teil, sollen wir das gegbene Programm hinsichtlich der zurückgelegten Distanz des Roboters verändern. Dabei soll die Distanz maximiert werden. Die benötigten Funktionen könnte man selbst implentieren, aber für Python können wir wieder Counter und permutations aus itertools nutzen und brauchen daher folgende Imports.

1
2
from collections import Counter
from itertools import permutations

Für die Optimierung brauchen wir im Wesentlichen zwei Dinge: 1. Alle möglichen Varianten unseres Programms und 2. eine Berechnungsvorschrift für die Distanz. Den ersten Punkt bekommen wir wie gesagt über Counter und permutations und die Distanz haben wir ja bereits im ersten Teil abgehakt. So müssen wir eigentlich nur noch über die Permutationen iterieren, die Distanzen bestimmen und uns merken, wann diese ihren Maximalwert erreicht hat.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def optimize_program(order: str, program: str) -> tuple[int, str]:
    best: int = -1
    best_program: str = ""
    counts = Counter(program)
    for perm in permutations(counts):
        cand = "".join(c * counts[c] for c in perm)
        d = calculate_distance(order, cand)
        if d > best:
            best, best_program = d, cand
    return best, best_program

def partwo():
    # test cases (given by task)
    program = ["rybryb", "vrvbvg", "groovyyoyo", "roygbvroygbvroygbv"]
    for prog in program:
        dist, opt_prog = optimize_program("roygbv", prog)
        print(f"optimized: {opt_prog} distance: {dist}")

    INPUT = readfile(FILENAME)
    dist, opt_prog = optimize_program("roygbv", INPUT)
    print(f"optimized: {opt_prog} distance: {dist}")

Die Aufgabe war mMn. insgesamt schwerer als die Aufgabe von Tag eins. Wie gesagt hatte ich die meisten Schwierigkeiten im ersten Teil. Eine sinnvolle Lösung sezt sich eben meist aus Verständnis und dem Programmieren zusammen.

Advent of Code 2026 - Dieser Artikel ist Teil einer Serie.
Teil : Dieser Artikel

Verwandte Artikel