Advent of Code - Programmieraufgaben im Adventskalender

Laudian

Moderator
Moin Moin,

Nachdem die Idee letztes Jahr recht erfolgreich war, gibt es auf adventofcode.com/ auch dieses Jahr jeden Tag wieder 2 kleine Programmieraufgaben.

Letztes Jahr wurde ich durch diesen Post hier im Forum leider erst relativ spät auf die Aktion aufmerksam.

Da ich die Sache insbesondere für Hobbyprogrammierer sehr interessant finde, wollte ich hier noch einmal darauf aufmerksam machen. Die Aufgaben fangen in den ersten Tagen relativ einfach an und werden zum Ende hin dann immer kniffliger.

Außerdem würde es mich freuen, wenn sich hier noch ein paar andere Leute finden, welche die Aufgaben auch lösen und daran interessiert sind, ihren Code hier mit anderen zu vergleichen. Mich würde es einfach interessieren, wie andere Leute an die Aufgaben herangehen und wie die Lösungen in anderen Sprachen aussehen (ich schreibe in Python).

Fragen zu Problemen oder Verbesserungsvorschläge zu gepostetem Code sind natürlich auch gern gesehen.

Lösungen:
Tag 1:
Aufgabe 1:
Code:
eingabe = """R4, R4, L1, R3, L5, R2, R5, R1, L4, R3, L5, R2, L3, L4, L3, R1, R5, R1, L3, L1, R3, L1, R2, R2, L2, R5, L3, L4, R4, R4, R2, L4, L1, R5, L1, L4, R4, L1, R1, L2, R5, L2, L3, R2, R1, L194, R2, L4, R49, R1, R3, L5, L4, L1, R4, R2, R1, L5, R3, L5, L4, R4, R4, L2, L3, R78, L5, R4, R191, R4, R3, R1, L2, R1, R3, L1, R3, R4, R2, L2, R1, R4, L5, R2, L2, L4, L2, R1, R2, L3, R5, R2, L3, L3, R3, L1, L1, R5, L4, L4, L2, R5, R1, R4, L3, L5, L4, R5, L4, R5, R4, L3, L2, L5, R4, R3, L3, R1, L5, R5, R1, L3, R2, L5, R5, L3, R1, R4, L5, R4, R2, R3, L4, L5, R3, R4, L5, L5, R4, L4, L4, R1, R5, R3, L1, L4, L3, L4, R1, L5, L1, R2, R2, R4, R4, L5, R4, R1, L1, L1, L3, L5, L2, R4, L3, L5, L4, L1, R3"""

eingabe = eingabe.split(", ")

instructions = []

for instruction in eingabe:
	instructions.append((instruction[0:1], int(instruction[1:])))

NORTH = (0, 1)
SOUTH = (0, -1)
WEST = (-1, 0)
EAST = (1, 0)

Directions = (NORTH, EAST, SOUTH, WEST)

cDir = 0
cCoords = [0,0]

def changeDir(turn):
    global cDir
    if turn == "R":
        cDir = (cDir+1)%4
    elif turn == "L":
        cDir = (cDir % 4 - 1) % 4
    return

def addSteps(steps):
    global cCoords
    for i in (0,1):
        cCoords[i] += Directions[cDir][i]*steps
    return

for instruction in instructions:
    changeDir(instruction[0])
    addSteps(instruction[1])

print(abs(cCoords[0])+abs(cCoords[1]))
Aufgabe 2:
Code:
eingabe = """R4, R4, L1, R3, L5, R2, R5, R1, L4, R3, L5, R2, L3, L4, L3, R1, R5, R1, L3, L1, R3, L1, R2, R2, L2, R5, L3, L4, R4, R4, R2, L4, L1, R5, L1, L4, R4, L1, R1, L2, R5, L2, L3, R2, R1, L194, R2, L4, R49, R1, R3, L5, L4, L1, R4, R2, R1, L5, R3, L5, L4, R4, R4, L2, L3, R78, L5, R4, R191, R4, R3, R1, L2, R1, R3, L1, R3, R4, R2, L2, R1, R4, L5, R2, L2, L4, L2, R1, R2, L3, R5, R2, L3, L3, R3, L1, L1, R5, L4, L4, L2, R5, R1, R4, L3, L5, L4, R5, L4, R5, R4, L3, L2, L5, R4, R3, L3, R1, L5, R5, R1, L3, R2, L5, R5, L3, R1, R4, L5, R4, R2, R3, L4, L5, R3, R4, L5, L5, R4, L4, L4, R1, R5, R3, L1, L4, L3, L4, R1, L5, L1, R2, R2, R4, R4, L5, R4, R1, L1, L1, L3, L5, L2, R4, L3, L5, L4, L1, R3"""

eingabe = eingabe.split(", ")

instructions = []

for instruction in eingabe:
	instructions.append((instruction[0:1], int(instruction[1:])))

NORTH = (0, 1)
SOUTH = (0, -1)
WEST = (-1, 0)
EAST = (1, 0)

Directions = (NORTH, EAST, SOUTH, WEST)

cDir = 0
cCoords = [0,0]

def changeDir(turn):
    global cDir
    if turn == "R":
        cDir = (cDir+1)%4
    elif turn == "L":
        cDir = (cDir % 4 - 1) % 4
    return

def addSteps(steps):
    global cCoords
    for i in (0,1):
        cCoords[i] += Directions[cDir][i]*steps
    return

visitedLocations = [(0,0)]

def execute():
    for instruction in instructions:
        changeDir(instruction[0])
        for n in range(instruction[1]):
            addSteps(1)
            coords = tuple(cCoords)
            if coords in visitedLocations:
                return coords
            else:
                visitedLocations.append(coords)
execute()
print(abs(cCoords[0])+abs(cCoords[1]))
Tag 2:
Aufgabe 1:
Code:
eingabe = """DULUDRDDDRLUDURUUULRRRURDRDULRUDDUDRULUDDUDRLDULRRLRDRUDUUULUUDLRURDUDDDDRDLLLLULRDLDRDLRLULRUURDDUULUDLRURRDDRDDRDDLDRDLLUURDRUULRRURURRDLRLLLUDULULULULUDRLLRUDUURLDRLRLRDRRDRLLLDURRDULDURDDRLURRDURLRRRLDLLLDRUUURLRDLDLLLLRDURRLDLULRLDDLDLURLRRDDRUDDUULRURRUDLRDLDUURDDDDRLRURUDULUDLRRLLLLLRDRURLLDLDULUUDLUDDDRLLDRRUDLLURRUUDDRRLLRRLDDDURLDRDRLURRRRDRRRDDUDULULDURRUUURRRDULUUUDDRULDRLLRDLDURLURRLLRUUUULRDURLLDDRLLDLRLRULUUDRURUDLLURUDDRDURLRDRRRDURLDDRDRLRLLURULUUULUDDDULDLRDDDRDLLRRLDRDULLUUUDLDDLDDDLLLLLLLDUDURURDURDRUURRRDDRDUDLULDURDUDURDDDRULDURURURRLURLURLUURLULDLLRUULURDDRLRDDLRDLRRR
LUURLRUDRRUDLLDLUDDURULURLUUDUUDDRLUULRDUDDUULDUUDRURDDRRDRLULLRDRDLRLLUURRUULRLDRULUDLDUUDDDRDDLRDLULDRLDUULDLRDLLLDLDLRDUULUDURRULLRLDUDRLLLULUUUULUUDUUURRRDULLUURUDRRLDURRUULDRDULDUDRDUUULUUDDRLUDRLDLDRUUURDLDUDRUDUURLLRRLRLLRRLDULDDULUDUUURULDDUDUDRURRDLULRUDDURDLDLLRRRLDRLULLLRUULDUDLUUDURRLLLRLUDURRDDLDRDDDLURDLDRRUDUDLUDULULRUUUDLUURLLRLDDLURULDURDLRRDDDDURLDDLLDDULLLRLDLDULDUUDDRLDUURDDLDLUUDULRRLRLUURURUURLRLURUURLDRUURLLRDDUUUDULUDDDRDRLDRDRRLRLDULLRRUDLURULULRDRURURLULDUDLRURLRDDRULDDLRD
LUDRULUULRRDDDDRRDUURUDDRLDDLDRDURRURULRDLDLDUUDRRDUUDUDLLLRRLDUDDRLDDLRRLRDRLUDLULUDDUUDULDUUULUDLDDURLDURUDLDRUUDRLRRLDLDDULDUUDDLDDLLURDRLRUURDDRUDDUDLDRRLRUDRUULRRRLRULULURDLRRURDRLRULDDDRDUULLURUUUURUDDLRRRRRDURLULDLUULUDRRUDUDRRDDRURDURLRLUDDLDLRRULUDLDDRLDDLDDDLLLLRDLLUULDDLULDLDRDDUDLURUDLDLDDRRUUDDDLRLLLDRRDDDUURDUDURUURRDRLLDUDLDUULLDLDLLUULLRRULDLDRURLDULDRUURDURRURDLRDLLLDRRUDRUUDRURLUDDRURLDURRDLUUDLUUDULLLDDDDRRDLLLDLURULDDRDLUUURRDRRUUDDUL
DUUULDUDDDURLLULDDLLUDURLLLURULULURUURDRURLRULLLLDRDDULRRDRRLLLRDDDUULLRRURRULLDDURRRLRDDLULDULLDUDLURRDLDDLURDLRLLDRURLLRLLRRRDRRRURURUUDDLLDDLDDDLRLURUUUULRDLUDDDURLLDDRLDRRLLUDUUULRLLDRRRLRUUDLDUULRLUDRULLLLDUDLLUUDDRUURLURUDRDDDLRURUDRLULLULUUDLDURDULRRDRLDURUULRDRRRDRDRRLRLRDDUULLRDLDURDDDULURRLULDDURDURDDUDURDLLUUULUDULRDDLDRDRUDLLUURDLRDURURULURULLDRLLRRULDLULULDLULRURLRRLUDLLLRLUDLURLULDULDRLLLDLDDDDRDRLRRLRDULUUDULDDLDURDLLLDDDDLLUURRDURLDLUDDLULRUUUDDRRLDLLLRDLLDRRRDDLULLURDDRRRRLDLRLLLRL
LULLRRDURRLDUUDRRURLURURRRLRDRUULUULURLLURRDRULRDURDDDDUULLLLDUULDLULURDRLDLULULDRLLDLLRLRULURUDRUUDULRULLLUDRULUDRLLUDLDRRDRUUURURLRDURDRLRDDDURLURRDLRUUUDUURULULDLUULRDLRRRDRDRLLLDLRRDRLLDDULDRUDRRLULLRDLDUDDULRDDLULRURULRLLLULDLLLLRDLDRURUDUURURLDRLUULLDUDULUDDDULUDLRUDDUDLULLUULUUURULURRULRDDURDDLURLRRDRDLDULRLRDRRRULRDDDRLLDDDDRRRRDRDLULUURDURULDLRDULDUDLDURUDLUDLUDDDUDURDURDDURLLRUDUURRRUDRRRRULLLLDDDLUULLUULRRRULDLURDLULRULDRLR"""

eingabe = eingabe.split("\n")

class Coord(tuple):
    def __add__(self, b):
        result = (self[0]+b[0], self[1]+b[1])
        return result

    def __sub__(a, b):
        result = (a[0]-b[0], a[1]-b[1])
        return result

keypad = {(0,2):1, (1,2):2, (2,2):3,
          (0,1):4, (1,1):5, (2,1):6,
          (0,0):7, (1,0):8, (2,0):9}

move = {"U":(0,1), "D":(0,-1), "L":(-1, 0), "R":(1, 0)}


pos = Coord((1,1))

def execute():
    global pos
    string = ""
    for instruction in eingabe:
        for letter in instruction:
            newPos = pos + move[letter]
            if newPos in keypad.keys():
                pos = Coord(newPos)
        string += str(keypad[pos])
    print(string)
    return

execute()
Aufgabe 2:
Code:
eingabe = """DULUDRDDDRLUDURUUULRRRURDRDULRUDDUDRULUDDUDRLDULRRLRDRUDUUULUUDLRURDUDDDDRDLLLLULRDLDRDLRLULRUURDDUULUDLRURRDDRDDRDDLDRDLLUURDRUULRRURURRDLRLLLUDULULULULUDRLLRUDUURLDRLRLRDRRDRLLLDURRDULDURDDRLURRDURLRRRLDLLLDRUUURLRDLDLLLLRDURRLDLULRLDDLDLURLRRDDRUDDUULRURRUDLRDLDUURDDDDRLRURUDULUDLRRLLLLLRDRURLLDLDULUUDLUDDDRLLDRRUDLLURRUUDDRRLLRRLDDDURLDRDRLURRRRDRRRDDUDULULDURRUUURRRDULUUUDDRULDRLLRDLDURLURRLLRUUUULRDURLLDDRLLDLRLRULUUDRURUDLLURUDDRDURLRDRRRDURLDDRDRLRLLURULUUULUDDDULDLRDDDRDLLRRLDRDULLUUUDLDDLDDDLLLLLLLDUDURURDURDRUURRRDDRDUDLULDURDUDURDDDRULDURURURRLURLURLUURLULDLLRUULURDDRLRDDLRDLRRR
LUURLRUDRRUDLLDLUDDURULURLUUDUUDDRLUULRDUDDUULDUUDRURDDRRDRLULLRDRDLRLLUURRUULRLDRULUDLDUUDDDRDDLRDLULDRLDUULDLRDLLLDLDLRDUULUDURRULLRLDUDRLLLULUUUULUUDUUURRRDULLUURUDRRLDURRUULDRDULDUDRDUUULUUDDRLUDRLDLDRUUURDLDUDRUDUURLLRRLRLLRRLDULDDULUDUUURULDDUDUDRURRDLULRUDDURDLDLLRRRLDRLULLLRUULDUDLUUDURRLLLRLUDURRDDLDRDDDLURDLDRRUDUDLUDULULRUUUDLUURLLRLDDLURULDURDLRRDDDDURLDDLLDDULLLRLDLDULDUUDDRLDUURDDLDLUUDULRRLRLUURURUURLRLURUURLDRUURLLRDDUUUDULUDDDRDRLDRDRRLRLDULLRRUDLURULULRDRURURLULDUDLRURLRDDRULDDLRD
LUDRULUULRRDDDDRRDUURUDDRLDDLDRDURRURULRDLDLDUUDRRDUUDUDLLLRRLDUDDRLDDLRRLRDRLUDLULUDDUUDULDUUULUDLDDURLDURUDLDRUUDRLRRLDLDDULDUUDDLDDLLURDRLRUURDDRUDDUDLDRRLRUDRUULRRRLRULULURDLRRURDRLRULDDDRDUULLURUUUURUDDLRRRRRDURLULDLUULUDRRUDUDRRDDRURDURLRLUDDLDLRRULUDLDDRLDDLDDDLLLLRDLLUULDDLULDLDRDDUDLURUDLDLDDRRUUDDDLRLLLDRRDDDUURDUDURUURRDRLLDUDLDUULLDLDLLUULLRRULDLDRURLDULDRUURDURRURDLRDLLLDRRUDRUUDRURLUDDRURLDURRDLUUDLUUDULLLDDDDRRDLLLDLURULDDRDLUUURRDRRUUDDUL
DUUULDUDDDURLLULDDLLUDURLLLURULULURUURDRURLRULLLLDRDDULRRDRRLLLRDDDUULLRRURRULLDDURRRLRDDLULDULLDUDLURRDLDDLURDLRLLDRURLLRLLRRRDRRRURURUUDDLLDDLDDDLRLURUUUULRDLUDDDURLLDDRLDRRLLUDUUULRLLDRRRLRUUDLDUULRLUDRULLLLDUDLLUUDDRUURLURUDRDDDLRURUDRLULLULUUDLDURDULRRDRLDURUULRDRRRDRDRRLRLRDDUULLRDLDURDDDULURRLULDDURDURDDUDURDLLUUULUDULRDDLDRDRUDLLUURDLRDURURULURULLDRLLRRULDLULULDLULRURLRRLUDLLLRLUDLURLULDULDRLLLDLDDDDRDRLRRLRDULUUDULDDLDURDLLLDDDDLLUURRDURLDLUDDLULRUUUDDRRLDLLLRDLLDRRRDDLULLURDDRRRRLDLRLLLRL
LULLRRDURRLDUUDRRURLURURRRLRDRUULUULURLLURRDRULRDURDDDDUULLLLDUULDLULURDRLDLULULDRLLDLLRLRULURUDRUUDULRULLLUDRULUDRLLUDLDRRDRUUURURLRDURDRLRDDDURLURRDLRUUUDUURULULDLUULRDLRRRDRDRLLLDLRRDRLLDDULDRUDRRLULLRDLDUDDULRDDLULRURULRLLLULDLLLLRDLDRURUDUURURLDRLUULLDUDULUDDDULUDLRUDDUDLULLUULUUURULURRULRDDURDDLURLRRDRDLDULRLRDRRRULRDDDRLLDDDDRRRRDRDLULUURDURULDLRDULDUDLDURUDLUDLUDDDUDURDURDDURLLRUDUURRRUDRRRRULLLLDDDLUULLUULRRRULDLURDLULRULDRLR"""

eingabe = eingabe.split("\n")

class Coord(tuple):
    def __add__(self, b):
        result = (self[0]+b[0], self[1]+b[1])
        return result

    def __sub__(a, b):
        result = (a[0]-b[0], a[1]-b[1])
        return result

keypad = {(2,4):1, (1,3):2, (2,3):3,
          (3,3):4, (0,2):5, (1,2):6,
          (2,2):7, (3,2):8, (4,2):9,
          (1,1):"A", (2,1):"B", (3,1):"C", (2,0):"D"}

move = {"U":(0,1), "D":(0,-1), "L":(-1, 0), "R":(1, 0)}


pos = Coord((0,2))

def execute():
    string = ""
    global pos
    for instruction in eingabe:
        for letter in instruction:
            newPos = pos + move[letter]
            if newPos in keypad.keys():
                pos = Coord(newPos)
        string += str(keypad[pos])
    print(string)
    return

execute()
Tag 3:
Aufgabe 1:
Code:
file = open("day03_1.txt", "r")

eingabe = file.read()
eingabe = eingabe.split("\n")

instructions = []

for line in eingabe:
    while "  " in line:
        line = line.replace("  ", " ")
    line = line.strip().split(" ")
    instructions.append([int(x) for x in line])

def isPossibleTriangle(instruction):
    a, b, c = instruction
    if (a+b) > c and (a+c) > b and (c+b) > a:
        return True
    else:
        return False

counter = 0

for instruction in instructions:
    counter += isPossibleTriangle(instruction)

print(counter)
Aufgabe 2:
Code:
file = open("day03_1.txt", "r")

eingabe = file.read()
eingabe = eingabe.replace("\n", " ").strip()

while "  " in eingabe:
    eingabe = eingabe.replace("  ", " ")
eingabe = eingabe.split(" ")
    
instructions = []

for x in eingabe:
    instructions.append(int(x))

triangles = []

while len(instructions) > 0:
    a = instructions.pop(-9)
    b = instructions.pop(-8)
    c = instructions.pop(-7)
    d = instructions.pop(-6)
    e = instructions.pop(-5)
    f = instructions.pop(-4)
    g = instructions.pop(-3)
    h = instructions.pop(-2)
    i = instructions.pop(-1)

    triangles.append((i, f, c))
    triangles.append((h, e, b))
    triangles.append((g, d, a))

def isPossibleTriangle(instruction):
    a, b, c = instruction
    if (a+b) > c and (a+c) > b and (c+b) > a:
        return True
    else:
        return False

counter = 0

for instruction in triangles:
    counter += isPossibleTriangle(instruction)

print(counter)
Tag 4:
Aufgabe 1&2:
Code:
from operator import itemgetter

file = open("day04_1.txt", "r")
eingabe = file.read().split("\n")

instructions = []

for line in eingabe:
    line = line.strip("]")
    a, b = line.split("[")
    checksum = b
    c = a.split("-")
    sectorID = int(c.pop())
    string = "".join(c)
    instructions.append((string, sectorID, checksum, c))

realrooms = []

def isRealRoom(room):
    string, sectorID, checksum, oldstring = room
    string = "".join(sorted(string))
    copy = string
    counter = []
    while len(copy) > 0:
        letter = copy[0]
        x = copy.count(letter)
        counter.append((letter, x))
        copy = copy.replace(letter, "")
    counter = sorted(counter,key=itemgetter(1), reverse=True)
    check = []
    for n in reversed(range(1, counter[0][1]+1)):
        sublist = []
        for element in counter:
            if element[1] == n:
                sublist.append(element)
        sublist = sorted(sublist,key=itemgetter(0))
        for item in sublist:
            check.append(item[0])
    if "".join(check).startswith(checksum):
        return True
    else:
        return False
        
            

abc = list("abcdefghijklmnopqrstuvwxyz")
abc_dict = {}
for x in range(26):
    abc_dict[x] = abc[x]
    abc_dict[abc[x]] = x
            
x = 0
realrooms = []
for room in instructions:
    if isRealRoom(room):
        x += room[1]
        rotate = room[1] % 26
        decrypted = ""
        for string in room[3]:
            newstring = ""
            for letter in string:
                newstring += abc_dict[(abc_dict[letter] + rotate) % 26]
            decrypted += newstring+" "
        realrooms.append((decrypted.strip(), room[1]))
print(x)
for room in realrooms:
	if "north" in room[0]:
		print(room)
Tag 5:
Aufgabe 1:
Code:
import hashlib

eingabe = "reyedfim"

password = ""
index = 0
while len(password) < 8:
    string = eingabe + str(index)
    md5hash = hashlib.md5(string.encode()).hexdigest()
    if md5hash.startswith("00000"):
        password += md5hash[5]
        print(password)
    index += 1
Aufgabe 2:
Code:
import hashlib

eingabe = "reyedfim"

password = [False, False, False, False, False, False, False, False]
index = 0
while False in password:
    string = eingabe + str(index)
    md5hash = hashlib.md5(string.encode()).hexdigest()
    if md5hash.startswith("00000"):
        try:
            if password[int(md5hash[5])] == False:
                password[int(md5hash[5])] = md5hash[6]
                print(password)
        except:
            pass
    index += 1

print("".join(password))
Tag 6:
Code:
import collections

file = open("day06_1.txt", "r")
eingabe = file.read().split("\n")

strings = []
for i in range(len(eingabe[0])):
    string = ""
    for element in eingabe:
        string += element[i]
    strings.append(string)

result = ""
result2 = ""

for string in strings:
    result += str(collections.Counter(string).most_common()[0][0])
    result2 += str(collections.Counter(string).most_common()[-1][0])

print(result)
print(result2)
 
Zuletzt bearbeitet:
Interessante Aktion, danke für den Hinweis :daumen:

Ich werd mich heute Abend mal ransetzen und meine Lösungen (Werde vermutlich in C++ oder C# arbeiten) hier posten.

Tag 1
Aufgabe 1
Code:
using System;
using System.Linq;


namespace D1E1 {


    enum Direction { NORTH, EAST, SOUTH, WEST, DIRECTION_AMOUNT };


    struct Position {
        public int x;
        public int y;


        public Position(int _x, int _y) {
            x = _x;
            y = _y;
        }
    }


    class Program {


        private static Direction currentDir = Direction.NORTH;
        private static Position currentPos = new Position(0, 0);


        private static void TurnRight() {
            if (++currentDir == Direction.DIRECTION_AMOUNT) {
                currentDir = Direction.NORTH;
            }
        }


        private static void TurnLeft() {
            if ((int)(--currentDir) == -1) {
                currentDir = Direction.WEST;
            }
        }


        private static void Walk(int steps) {
            switch (currentDir) {
                case Direction.NORTH:
                    currentPos.y += steps;
                    break;
                case Direction.SOUTH:
                    currentPos.y -= steps;
                    break;
                case Direction.EAST:
                    currentPos.x += steps;
                    break;
                case Direction.WEST:
                    currentPos.x -= steps;
                    break;
            }
        }


        private static int GetDistance() {
            return Math.Abs(currentPos.x) + Math.Abs(currentPos.y);
        }


        private static bool ProcessInput(string[] args) {
            foreach (string s in args) {
                string command = s.Contains(',') ? s.Remove(s.Length - 1) : s;
                if (command[0].Equals('R')) {
                    TurnRight();
                } else {
                    TurnLeft();
                }
                try {
                    Walk(int.Parse(command.Substring(1)));
                } catch (Exception e) {
                    Console.WriteLine("Invalid input: " + command);
                    return false;
                }
            }


            return true;
        }


        static void Main(string[] args) {
            if (ProcessInput(args)) {
                Console.WriteLine("Distance: " + GetDistance());
            }
        }
    }
}
Aufgabe 2
Code:
using System;
using System.Collections.Generic;
using System.Linq;


namespace D1E2 {


    enum Direction { NORTH, EAST, SOUTH, WEST, DIRECTION_AMOUNT };


    struct Position : IEquatable<Position> {
        public int x;
        public int y;


        public Position(int _x, int _y) {
            x = _x;
            y = _y;
        }


        public bool Equals(Position other) {
            return x == other.x && y == other.y;
        }
    }


    class Program {


        private static Direction currentDir = Direction.NORTH;
        private static Position currentPos = new Position(0, 0);


        private static List<Position> visitedPositions = new List<Position>();


        private static void TurnRight() {
            if (++currentDir == Direction.DIRECTION_AMOUNT) {
                currentDir = Direction.NORTH;
            }
        }


        private static void TurnLeft() {
            if ((int)(--currentDir) == -1) {
                currentDir = Direction.WEST;
            }
        }


        private static void Walk(int steps) {
            if (steps > 0) {
                Position newPos = new Position(currentPos.x, currentPos.y);
                switch (currentDir) {
                    case Direction.NORTH:
                        newPos.y += 1;
                        break;
                    case Direction.SOUTH:
                        newPos.y -= 1;
                        break;
                    case Direction.EAST:
                        newPos.x += 1;
                        break;
                    case Direction.WEST:
                        newPos.x -= 1;
                        break;
                }


                if (visitedPositions.Contains(newPos)) {
                    Console.WriteLine("Distance: " + GetDistance(newPos));
                    Environment.Exit(0);
                } else {
                    visitedPositions.Add(newPos);
                    currentPos = newPos;
                    Walk(steps - 1);
                }
            }
        }


        private static int GetDistance(Position pos) {
            return Math.Abs(pos.x) + Math.Abs(pos.y);
        }


        private static void ProcessInput(string[] args) {
            foreach (string s in args) {
                string command = s.Contains(',') ? s.Remove(s.Length - 1) : s;
                if (command[0].Equals('R')) {
                    TurnRight();
                } else {
                    TurnLeft();
                }
                try {
                    Walk(int.Parse(command.Substring(1)));
                } catch (Exception e) {
                    Console.WriteLine("Invalid input: " + command);
                    return;
                }
            }
        }


        static void Main(string[] args) {
            visitedPositions.Add(currentPos);
            ProcessInput(args);
        }
    }
}

Tag 2
Aufgabe 1
Code:
using System;


namespace D2E1 {


    enum Direction { UP, DOWN, LEFT, RIGHT, DIRECTION_AMOUNT }


    struct Position {
        public int x;
        public int y;




        public Position(int _x, int _y) {
            x = _x;
            y = _y;
        }
    }


    class Program {


        private static int[,] keypad = new int[3, 3] {    { 1, 2, 3 }, 
                                                        { 4, 5, 6 }, 
                                                        { 7, 8, 9 } };
        private static Position pos = new Position(1, 1);
        private static string code = "";


        private static void Move(Direction dir) {
            switch(dir) {
                case Direction.DOWN:
                    pos.y = ++pos.y > 2 ? 2 : pos.y;
                    break;
                case Direction.UP:
                    pos.y = --pos.y < 0 ? 0 : pos.y;
                    break;
                case Direction.LEFT:
                    pos.x = --pos.x < 0 ? 0 : pos.x;
                    break;
                case Direction.RIGHT:
                    pos.x = ++pos.x > 2 ? 2 : pos.x;
                    break;
            }
        }


        private static void ProcessInput(string[] args) {
            foreach (string s in args) {
                foreach (char c in s) {
                    switch (c) {
                        case 'U':
                            Move(Direction.UP);
                            break;
                        case 'D':
                            Move(Direction.DOWN);
                            break;
                        case 'L':
                            Move(Direction.LEFT);
                            break;
                        case 'R':
                            Move(Direction.RIGHT);
                            break;
                    }
                }


                code += keypad[pos.y, pos.x];
            }
        }


        static void Main(string[] args) {
            ProcessInput(args);
            Console.WriteLine("Code: " + code);
        }
    }
}
Aufgabe 2
Code:
using System;


namespace D2E2 {


    enum Direction { UP, DOWN, LEFT, RIGHT, DIRECTION_AMOUNT }


    struct Position {
        public int x;
        public int y;


        public Position(int _x, int _y) {
            x = _x;
            y = _y;
        }
    }


    class Program {


        private static char[,] keypad = new char[5, 5] {    { '\0', '\0', '1', '\0', '\0' },
                                                            { '\0',  '2', '3',  '4', '\0' },
                                                            {  '5',  '6', '7',  '8',  '9' },
                                                            { '\0',  'A', 'B',  'C', '\0' },
                                                            { '\0', '\0', 'D', '\0', '\0' }, };
        private static Position pos = new Position(0, 2);
        private static string code = "";


        private static void Move(Direction dir) {
            switch (dir) {
                case Direction.DOWN:
                    pos.y = ++pos.y > 4 || keypad[pos.y, pos.x] == '\0' ? --pos.y : pos.y;
                    break;
                case Direction.UP:
                    pos.y = --pos.y < 0 || keypad[pos.y, pos.x] == '\0' ? ++pos.y : pos.y;
                    break;
                case Direction.LEFT:
                    pos.x = --pos.x < 0 || keypad[pos.y, pos.x] == '\0' ? ++pos.x : pos.x;
                    break;
                case Direction.RIGHT:
                    pos.x = ++pos.x > 4 || keypad[pos.y, pos.x] == '\0' ? --pos.x : pos.x;
                    break;
            }
        }


        private static void ProcessInput(string[] args) {
            foreach (string s in args) {
                foreach (char c in s) {
                    switch (c) {
                        case 'U':
                            Move(Direction.UP);
                            break;
                        case 'D':
                            Move(Direction.DOWN);
                            break;
                        case 'L':
                            Move(Direction.LEFT);
                            break;
                        case 'R':
                            Move(Direction.RIGHT);
                            break;
                    }
                }


                code += keypad[pos.y, pos.x];
            }
        }


        static void Main(string[] args) {
            ProcessInput(args);
            Console.WriteLine("Code: " + code);
        }
    }
}

Tag 3
Aufgabe 1
Code:
using System;
using System.IO;
using System.Text.RegularExpressions;


namespace D3E1 {
    class Program {


        private static void ProcessInput() {
            int validAmount = 0;
            try {
                StreamReader sr = new StreamReader("input.txt");
                while (!sr.EndOfStream) {
                    string line = sr.ReadLine();
                    line = Regex.Replace(line, @"\s+", " ");
                    string[] sides = line.Trim().Split(' ');


                    int sideA = int.Parse(sides[0]);
                    int sideB = int.Parse(sides[1]);
                    int sideC = int.Parse(sides[2]);


                    if (sideA + sideB > sideC && sideA + sideC > sideB && sideB + sideC > sideA) {
                        validAmount++;
                    }
                }
                sr.Close();


                Console.WriteLine("Valid Amount: " + validAmount);
            } catch (FormatException e) {
                Console.WriteLine("Parsing the input file failed:");
                Console.WriteLine(e.Message);
            } catch (Exception e) {
                Console.WriteLine("Couldn't open the input file:");
                Console.WriteLine(e.Message);
            }
        }


        static void Main(string[] args) {
            ProcessInput();
        }
    }
}
Aufgabe 2
Code:
using System;
using System.IO;
using System.Text.RegularExpressions;


namespace D3E2 {
    class Program {


        private static void ProcessInput() {
            int validAmount = 0;
            try {
                StreamReader sr = new StreamReader("input.txt");
                while (!sr.EndOfStream) {
                    string line = sr.ReadLine();
                    line = Regex.Replace(line, @"\s+", " ");
                    string[] sides1 = line.Trim().Split(' ');


                    string line2 = sr.ReadLine();
                    line2 = Regex.Replace(line2, @"\s+", " ");
                    string[] sides2 = line2.Trim().Split(' ');


                    string line3 = sr.ReadLine();
                    line3 = Regex.Replace(line3, @"\s+", " ");
                    string[] sides3 = line3.Trim().Split(' ');


                    for (int i = 0; i < 3; i++) {
                        int sideA = int.Parse(sides1[i]);
                        int sideB = int.Parse(sides2[i]);
                        int sideC = int.Parse(sides3[i]);


                        if (sideA + sideB > sideC && sideA + sideC > sideB && sideB + sideC > sideA) {
                            validAmount++;
                        }
                    }
                }
                sr.Close();


                Console.WriteLine("Valid Amount: " + validAmount);
            } catch (FormatException e) {
                Console.WriteLine("Parsing the input file failed:");
                Console.WriteLine(e.Message);
            } catch (Exception e) {
                Console.WriteLine("Couldn't open the input file:");
                Console.WriteLine(e.Message);
            }
        }


        static void Main(string[] args) {
            ProcessInput();
        }
    }
}

Tag 4
Aufgabe 1
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;


namespace D4E1 {
    class Program {


        private static List<Room> rooms = new List<Room>();


        private static void ProcessInput() {
            try {
                StreamReader sr = new StreamReader("input.txt");
                while (!sr.EndOfStream) {
                    string line = sr.ReadLine();
                    rooms.Add(new Room(line));
                }
                sr.Close();
            } catch (Exception e) {
                Console.WriteLine("Couldn't open the input file:");
                Console.WriteLine(e.Message);
            }


            int sum = 0;
            foreach (Room r in rooms) {
                if (r.IsValidRoom()) sum += r.GetSectorID();
            }


            Console.WriteLine("Sum: " + sum);
        }


        static void Main(string[] args) {
            ProcessInput();
        }
    }


    internal class Room {


        private Dictionary<char, int> encryptedName = new Dictionary<char, int>();
        private int sectorID;
        private string checksum;


        internal Room(string encryptedRoom) {
            string[] substrings = encryptedRoom.Split('-');


            for (int i = 0; i < substrings.Length; i++) {
                if (i < substrings.Length - 1) {
                    foreach (char c in substrings[i]) {
                        if (!encryptedName.ContainsKey(c)) {
                            encryptedName.Add(c, 1);
                        } else {
                            encryptedName[c]++;
                        }
                    }
                } else {
                    try {
                        sectorID = int.Parse(substrings[i].Substring(0, substrings[i].LastIndexOf("[")));
                        checksum = substrings[i].Substring(substrings[i].LastIndexOf("[") + 1, substrings[i].LastIndexOf("]") - substrings[i].LastIndexOf("[") - 1);
                    } catch (FormatException e) {
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }


        internal bool IsValidRoom() {
            List<KeyValuePair<char, int>> sortedList = encryptedName.ToList();
            sortedList.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value) == 0 ? pair1.Key.CompareTo(pair2.Key) : pair2.Value.CompareTo(pair1.Value));


            bool isValid = true;
            for (int i = 0; i < checksum.Length && isValid; i++) {
                isValid = checksum[i] == sortedList[i].Key;
            }


            return isValid;
        }


        internal int GetSectorID() {
            return sectorID;
        }
    }
}
Aufgabe 2 (Langsam wirds unübersichtlicher)
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;


namespace D4E {
    class Program {


        private static List<Room> rooms = new List<Room>();


        private static void FilterRooms() {
            for (int i = rooms.Count - 1; i >= 0; i--) {
                if (!rooms[i].IsValidRoom()) {
                    rooms.RemoveAt(i);
                }
            }
        }


        private static void ProcessInput() {
            try {
                StreamReader sr = new StreamReader("input.txt");
                while (!sr.EndOfStream) {
                    string line = sr.ReadLine();
                    rooms.Add(new Room(line));
                }
                sr.Close();
            } catch (Exception e) {
                Console.WriteLine("Couldn't open the input file:");
                Console.WriteLine(e.Message);
            }
        }


        static void Main(string[] args) {
            ProcessInput();
            FilterRooms();


            foreach (Room r in rooms) {
                if (r.GetDecryptedName().Contains("north")) {
                    Console.WriteLine(r.GetDecryptedName() + " SectorID: " + r.GetSectorID());
                }
            }


            Console.ReadKey();
        }
    }


    internal class Room {


        private Dictionary<char, int> nameDictionary = new Dictionary<char, int>();
        private int sectorID;
        private string checksum;
        private string encryptedName;


        internal Room(string encryptedRoom) {
            string[] substrings = encryptedRoom.Split('-');


            for (int i = 0; i < substrings.Length; i++) {
                if (i < substrings.Length - 1) {
                    encryptedName += substrings[i] + " ";
                    foreach (char c in substrings[i]) {
                        if (!nameDictionary.ContainsKey(c)) {
                            nameDictionary.Add(c, 1);
                        } else {
                            nameDictionary[c]++;
                        }
                    }
                } else {
                    try {
                        sectorID = int.Parse(substrings[i].Substring(0, substrings[i].LastIndexOf("[")));
                        checksum = substrings[i].Substring(substrings[i].LastIndexOf("[") + 1, substrings[i].LastIndexOf("]") - substrings[i].LastIndexOf("[") - 1);
                    } catch (FormatException e) {
                        Console.WriteLine(e.Message);
                    }
                }
            }


            encryptedName.TrimEnd();
        }


        internal bool IsValidRoom() {
            List<KeyValuePair<char, int>> sortedList = nameDictionary.ToList();
            sortedList.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value) == 0 ? pair1.Key.CompareTo(pair2.Key) : pair2.Value.CompareTo(pair1.Value));


            bool isValid = true;
            for (int i = 0; i < checksum.Length && isValid; i++) {
                isValid = checksum[i] == sortedList[i].Key;
            }


            return isValid;
        }


        internal int GetSectorID() {
            return sectorID;
        }


        private char RotateLetter(char letter, int amount) {
            int residual = amount % 26;
            int baseVal = char.ToLower(letter) - 'a';


            int returnVal = residual + baseVal;


            while (returnVal > 25) {
                returnVal -= 26;
            }


            return (char)(returnVal + 'a');
        }


        internal string GetDecryptedName() {
            if (!IsValidRoom()) {
                return null;
            } else {
                StringBuilder decryptedName = new StringBuilder();
                foreach (char c in encryptedName) {
                    if (c == ' ') {
                        decryptedName.Append(c);
                    } else {
                        decryptedName.Append(RotateLetter(c, sectorID));
                    }
                }


                return decryptedName.ToString();
            }
        }
    }
}

Tag 5
Aufgabe 1 (War bei mir auch erst recht langsam, dann hab ichs Multithreaded gebaut danach gings :D)
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;


namespace D5E1 {
    class Program {


        private static ulong searchedIndexes = 0;
        private static readonly Mutex searchedIndexesLock =  new Mutex();


        private static Dictionary<ulong, char> passwordDictionary = new Dictionary<ulong, char>();
        private static readonly Mutex passwordLock = new Mutex();


        private static string password = "";


        private static void Worker(string line) {
            UTF8Encoding encoding = new UTF8Encoding();
            MD5 md5hasher = MD5.Create();


            passwordLock.WaitOne();
            while(passwordDictionary.Count < 8) {
                passwordLock.ReleaseMutex();


                searchedIndexesLock.WaitOne();
                ulong startIndex = searchedIndexes;
                searchedIndexes += 30000;
                searchedIndexesLock.ReleaseMutex();


                for (ulong index = startIndex; index < startIndex + 30000; index++) {
                    byte[] byteLine = encoding.GetBytes(line + index);
                    byte[] hash = md5hasher.ComputeHash(byteLine);


                    string hex = BitConverter.ToString(hash);


                    if (hex.StartsWith("00-00-0")) {
                        Console.WriteLine("Letter Found: " + hex[7] + " at Index: " + index);
                        passwordLock.WaitOne();
                        passwordDictionary.Add(index, hex[7]);
                        passwordLock.ReleaseMutex();
                    }
                }




                passwordLock.WaitOne();
            }
            passwordLock.ReleaseMutex();
        }


        private static void ProcessInput() {
            Console.Write("Enter Door ID: ");
            string line = Console.ReadLine();


            List<Thread> threads = new List<Thread>();


            for (int i = 0; i < Environment.ProcessorCount; i++) {
                Thread thread = new Thread(() => Worker(line));
                thread.Start();
                threads.Add(thread);
            }


            foreach (Thread t in threads) {
                t.Join();
            }


            List<KeyValuePair<ulong, char>> sortedList = passwordDictionary.ToList();
            sortedList.Sort((pair1, pair2) => pair1.Key.CompareTo(pair2.Key));


            for (int i = 0; i < 8; i++) {
                password += sortedList[i].Value;
            }


        }




        static void Main(string[] args) {
            ProcessInput();
            Console.WriteLine("Password: " + password);
            Console.ReadKey();
        }
    }
}
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;


namespace D5E2 {
    class Program {


        private const int INDEXES_TO_CALC = 30000;


        private static int searchedIndexes = 0;
        private static readonly Mutex searchedIndexesLock = new Mutex();


        private static Dictionary<int, string> passwordDictionary = new Dictionary<int, string>();
        private static readonly Mutex passwordLock = new Mutex();


        private static string password = "";


        private static bool passwordFilled() {
            bool[] positions = new bool[8];


            foreach (KeyValuePair<int, string> entry in passwordDictionary) {
                positions[int.Parse(entry.Value.Substring(0, 1))] = true;
            }


            foreach (bool b in positions) {
                if (!b) {
                    return false;
                }
            }
            return true;
        }


        private static void Worker(string line) {
            UTF8Encoding encoding = new UTF8Encoding();
            MD5 md5hasher = MD5.Create();


            int indexSteps = INDEXES_TO_CALC;


            passwordLock.WaitOne();
            while (!passwordFilled()) {
                passwordLock.ReleaseMutex();


                searchedIndexesLock.WaitOne();
                int startIndex = searchedIndexes;
                searchedIndexes += indexSteps;
                searchedIndexesLock.ReleaseMutex();


                for (int index = startIndex; index < startIndex + indexSteps; index++) {
                    byte[] byteLine = encoding.GetBytes(line + index);
                    byte[] hash = md5hasher.ComputeHash(byteLine);
                    
                    if ((hash[0] | hash[1] | (hash[2] >> 4)) == 0) {
                        string hex = BitConverter.ToString(hash);
                        if (hex[7] >= '0' && hex[7] < '8') {
                            Console.WriteLine("Letter Found: " + hex.Substring(7, 3) + " at Index: " + index);
                            passwordLock.WaitOne();
                            passwordDictionary.Add(index, hex.Substring(7, 3));
                            passwordLock.ReleaseMutex();
                        }
                    }
                }


                passwordLock.WaitOne();
            }
            passwordLock.ReleaseMutex();


            return;
        }


        private static void ProcessInput() {
            Console.Write("Enter Door ID: ");
            string line = Console.ReadLine();


            int startTime = Environment.TickCount;


            List<Thread> threads = new List<Thread>();


            Console.Write("Enter Thread Amount: ");
            int threadCount = int.Parse(Console.ReadLine());
            for (int i = 0; i < threadCount; i++) {
                Thread thread = new Thread(() => Worker(line));
                thread.Start();
                threads.Add(thread);
            }


            foreach (Thread t in threads) {
                t.Join();
            }


            Console.WriteLine("Generation Took " + (Environment.TickCount - startTime) / 1000.0f + " Seconds");


            List<KeyValuePair<int, string>> sortedList = passwordDictionary.ToList();
            sortedList.Sort((pair1, pair2) => pair1.Key.CompareTo(pair2.Key));


            char[] pw = new char[8];


            for (int i = 0; i < 8; i++) {
                bool filled = false;
                for (int j = 0; j < sortedList.Count && !filled; j++) {
                    if (int.Parse(sortedList[j].Value.Substring(0, 1)) == i) {
                        filled = true;
                        pw[i] = sortedList[j].Value[2];
                    }
                }
            }


            for (int i = 0; i < 8; i++) {
                password += pw[i];
            }


        }


        static void Main(string[] args) {
            ProcessInput();
            Console.WriteLine("Password: " + password.ToLower());
            Console.ReadKey();
        }
    }
}
Tag 6
Aufgabe 1
Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;


namespace D6E1 {


    class Program {


        private static List<Dictionary<char, int>> dictionaries = new List<Dictionary<char, int>>();


        private static void ProcessInput() {
            try {
                StreamReader sr = new StreamReader("input.txt");
                while (!sr.EndOfStream) {
                    string line = sr.ReadLine();
                    int column = 0;
                    foreach(char c in line) {
                        if (dictionaries.Count < column + 1) {
                            dictionaries.Add(new Dictionary<char, int>());
                        }


                        if (!dictionaries[column].ContainsKey(c)) {
                            dictionaries[column].Add(c, 1);
                        } else {
                            dictionaries[column][c]++;
                        }


                        column++;
                    }
                }
                sr.Close();
            } catch (Exception e) {
                Console.WriteLine("Couldn't open the input file:");
                Console.WriteLine(e.Message);
            }
        }


        static void Main(string[] args) {
            ProcessInput();


            string password = "";
            foreach (Dictionary<char, int> dic in dictionaries) {
                List<KeyValuePair<char, int>> sortedList = dic.ToList();
                sortedList.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value) == 0 ? pair1.Key.CompareTo(pair2.Key) : pair2.Value.CompareTo(pair1.Value));


                password += sortedList[0].Key;
            }


            Console.WriteLine("Password: " + password);
        }
    }
}
Aufgabe 2
Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;


namespace D6E2 {


    class Program {


        private static List<Dictionary<char, int>> dictionaries = new List<Dictionary<char, int>>();


        private static void ProcessInput() {
            try {
                StreamReader sr = new StreamReader("input.txt");
                while (!sr.EndOfStream) {
                    string line = sr.ReadLine();
                    int column = 0;
                    foreach (char c in line) {
                        if (dictionaries.Count < column + 1) {
                            dictionaries.Add(new Dictionary<char, int>());
                        }


                        if (!dictionaries[column].ContainsKey(c)) {
                            dictionaries[column].Add(c, 1);
                        } else {
                            dictionaries[column][c]++;
                        }


                        column++;
                    }
                }
                sr.Close();
            } catch (Exception e) {
                Console.WriteLine("Couldn't open the input file:");
                Console.WriteLine(e.Message);
            }
        }


        static void Main(string[] args) {
            ProcessInput();


            string password = "";
            foreach (Dictionary<char, int> dic in dictionaries) {
                List<KeyValuePair<char, int>> sortedList = dic.ToList();
                sortedList.Sort((pair1, pair2) => pair1.Value.CompareTo(pair2.Value));


                password += sortedList[0].Key;
            }


            Console.WriteLine("Password: " + password);
        }
    }
}
Tag 7
Aufgabe 1 + 2
Code:
using System;
using System.Collections.Generic;
using System.IO;


namespace D7E1 {
	class Program {


		private static bool IsTLS(string line) {
			bool abba = false;
			bool hypernet = true;
			bool foundOpenBracket = false;
			for (int i = 0; i < line.Length - 3; i++) {
				if (line[i] == line[i + 3] && line[i + 1] == line[i + 2] && line[i] != line[i + 1]) {
					abba = true;
					if (foundOpenBracket) {
						hypernet = false;
					}
				}
				if (line[i] == '[') foundOpenBracket = true;
				if (line[i] == ']') foundOpenBracket = false;
			}


			return hypernet && abba;
		}


		private static bool IsSSL(string line) {
			List<string> aba = new List<string>();
			List<string> bab = new List<string>();


			bool foundOpenBracket = false;
			for (int i = 0; i < line.Length - 2; i++) {
				if (line[i] == line[i + 2] && line[i] != line[i + 1]) {
					if (!foundOpenBracket) aba.Add(line.Substring(i, 3));
					else bab.Add(line.Substring(i, 3));
				}
				if (line[i] == '[') foundOpenBracket = true;
				if (line[i] == ']') foundOpenBracket = false;
			}


			foreach (string s in aba) {
				string correspondingBAB = s[1].ToString() + s[0].ToString() + s[1].ToString();
				if (bab.Contains(correspondingBAB)) return true;
			}
			return false;
		}


		private static void ProcessInput() {
			try {
				StreamReader sr = new StreamReader("input.txt");
				int tlsCount = 0;
				int sslCount = 0;
				while (!sr.EndOfStream) {
					string line = sr.ReadLine();					
					if (IsTLS(line)) tlsCount++;
					if (IsSSL(line)) sslCount++;
				}
				Console.WriteLine("TLS Amount: " + tlsCount);
				Console.WriteLine("SSL Amount: " + sslCount);
				sr.Close();
			} catch (Exception e) {
				Console.WriteLine("Couldn't open the input file:");
				Console.WriteLine(e.Message);
			}
		}


		static void Main(string[] args) {
			ProcessInput();
		}
	}
}

Tipp zu Aufabe 2 Tag 1
Bei Aufgabe 2 von Tag 1 hing ich gerade 15 Minuten an dem Problem, dass ich die Schritte einzeln abgehen muss und nicht mehr aufaddieren kann wie bei Aufgabe 1, naja Nachzeichnen des Beispiels in Excel brachte Erleuchtung :ugly:

@Laudian
Bei Tag 3 Aufgabe 2 hast du folgendes gemacht:
Code:
if (a+b) > c and (a+c) > b and (c+b) > a:
        return True
    else:
        return False
warum nicht einfach
Code:
return (a+b) > c and (a+c) > b and (c+b) > a
?
 
Zuletzt bearbeitet:
Freut mich, dass zumindest einer schonmal mitmacht ;-)

@Laudian
Bei Tag 3 Aufgabe 2 hast du folgendes gemacht:
Code:
if (a+b) > c and (a+c) > b and (c+b) > a:
        return True
    else:
        return False
warum nicht einfach
Code:
return (a+b) > c and (a+c) > b and (c+b) > a
?

Da habe ich mir ehrlich gesagt überhaupt keine Gedanken drüber gemacht.
Ich mag kompakte Lösungen aber, werde ich mir für die Zukunft merken :daumen:

Wenn du jetzt meine Aufgabe 4 siehst... Da wirst du vor Schreck erstarren, so unsauber ist das geworden, weil ich zwischendurch immer wieder Teile umgeschrieben habe ^^
Da sind sogar glaube ich noch Zeilen drin, die überhaupt nicht benutzt werden...

Bei Aufgabe 5 würde mich deine Laufzeit auch mal interessieren. Mein Programm lief da ca. eine Minute lang, C++ sollte wohl deutlich schneller sein ?
 
Interessante Idee. Vielleicht werd ich mal spaßeshalber was davon in Matlab lösen. Irgendwie muss man ja langsamer als Python schaffen :fresse:
Da habe ich mir ehrlich gesagt überhaupt keine Gedanken drüber gemacht.
Ich mag kompakte Lösungen aber, werde ich mir für die Zukunft merken :daumen:
Solltest du jemals beruflich Coden wollen: Vergiss es direkt wieder. Lesbarkeit ist da oberstes Gebot.
 
Zuletzt bearbeitet:
Naja ich find das jetzt nicht so schlecht lesbar. Hab das aber auch von der Uni seit Anfang an so eingeprügelt bekommen, ist vielleicht einfach Gewohnheitssache.

Edit:
Hab Tag 5 A2 jetzt fertig für bessere Vergleichbarkeit der Performance hab ich meine Lösung einfach mal im Anhang angehängt. Wer möchte kann ja mal gegentesten ;)

Edit2:
Hab grad mal dein Python Script bei mir laufen lassen, ist knapp 30 Sekunden schneller als mein C# Programm oO
Entweder hab ich da irgendwo gewaltig mist gebaut, oder ich berechne zu viel unnötigen kram damit der Multithreading kram läuft. (Stichwort ThreadSafe und so)

Edit3:
Hab grade nochmal n paar String Operationen rausgeworfen die ich nur wegen komfort zur weiterverarbeitung drin hatte, hat auch ein paar Sekunden gebracht aber irgendwie ist es immer noch langsamer als ich erwartet hatte :/

Edit4:
Wie ich gerade herausgefunden habe, gibt es in C# anscheinend 2 Möglichkeiten um MD5 Hashes zu erstellen, wovon ich natürlich zuerst den deutlich langsameren Weg genommen habe :klatsch:
Jetzt entspricht die Performance schon eher dem was ich erwartet habe.

Edit5:
Grade noch eine unnötige Mutex Variable gefunden und entfernt, hat nochmal knapp 100% Performance freigeschaufelt :ugly:
Interessant ist nur, dass das ganze kaum mit steigender Threadanzahl skaliert oO
Wenn man die Threadanzahl abfragt, danach aber trotzdem mit der maximalen Threadanzahl arbeitet kann das ja auch keinen Unterschied machen was man eingibt. Es ist einfach schon zu spät :ugly:
 

Anhänge

  • D5E2.7z
    3,6 KB · Aufrufe: 35
Zuletzt bearbeitet:
Bin die Letzten Tage nicht wirklich dazu gekommen weiter zu machen, hab inzwischen wieder bis Tag 9 aufgeholt.
Da das Posten von Lösungen hier ein bisschen unübersichtlich geworden ist, lasse ich das jetzt Mal.

Wer sich meine Lösungen ansehen will kann sich gerne mein GitHub Repo angucken:
GitHub - Ebrithil95/AdventOfCode2016
 
Zurück