{ "cells": [ { "cell_type": "markdown", "id": "d0b07b88-208c-4408-b9c4-ac9d42b5bad0", "metadata": {}, "source": [ "# Vet mooi notebook van Bas" ] }, { "cell_type": "markdown", "id": "5016996d-7e00-44a1-9553-8dd95b864662", "metadata": {}, "source": [ "Laten we beginnen met de imports" ] }, { "cell_type": "code", "execution_count": 1, "id": "1e6ac084-5bf9-43f7-a7a6-8c8e20066159", "metadata": {}, "outputs": [], "source": [ "import re \n", "import numpy as np\n", "from functools import reduce\n", "from math import factorial" ] }, { "cell_type": "markdown", "id": "8f3db4f3-92c2-4e2c-91a2-fe59b1109673", "metadata": {}, "source": [ "## Puzzel 1" ] }, { "cell_type": "markdown", "id": "e76a322a-85e3-40b4-aa04-6f4dda2b7f40", "metadata": {}, "source": [ "### Deel 1" ] }, { "cell_type": "code", "execution_count": 2, "id": "98412978-4434-4461-8255-fde982948f26", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "55834" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f = open('data/puzzle_1.txt', 'r')\n", "total = 0\n", "for line in f:\n", " digit_1 = re.search('(\\d)', line).group()\n", " digit_2 = re.search('(?:\\d)(?!.*\\d)', line).group()\n", " total += int(digit_1+digit_2)\n", "total" ] }, { "cell_type": "markdown", "id": "00cbc4f3-d337-4702-bf25-d04717a1787b", "metadata": {}, "source": [ "### Deel 2" ] }, { "cell_type": "code", "execution_count": 3, "id": "66632939-dc5e-44ba-b740-868c20cabe8c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "53221" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']\n", "digits = '|'+'|'.join(l)\n", "f = open('data/puzzle_1.txt', 'r')\n", "total = 0\n", "for line in f:\n", " string_digits = re.findall('(?=(\\d'+digits+'))', line)\n", " string_digits = [digit if (digit not in l) else str(l.index(digit)+1) for digit in string_digits]\n", " total += int(string_digits[0] + string_digits[-1])\n", "total" ] }, { "cell_type": "markdown", "id": "455fa9e3-535d-4708-b0fe-1179ad095f4c", "metadata": {}, "source": [ "## Puzzel 2" ] }, { "cell_type": "code", "execution_count": 13, "id": "9c3695c6-20de-4e20-b13a-45c10eb26d0c", "metadata": {}, "outputs": [], "source": [ "data = open('data/puzzle_2.txt', 'r').readlines()" ] }, { "cell_type": "markdown", "id": "a1afaf93-e716-4347-83cb-8a5d3efd8601", "metadata": {}, "source": [ "### Deel 1" ] }, { "cell_type": "code", "execution_count": 14, "id": "eb4c93ee-5b08-47c7-b020-16b2c545b7c1", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3035" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "color_dict = {\n", " 'red': 12,\n", " 'green': 13,\n", " 'blue': 14\n", "}\n", "total = 0\n", "for line in data:\n", " possible = True\n", " for amount, color in re.findall('(\\d+)\\W*(red|green|blue)', line):\n", " if (color_dict[color] < int(amount)):\n", " possible = False\n", " if possible:\n", " total += int(re.findall('(\\d+)', line)[0])\n", "total" ] }, { "cell_type": "markdown", "id": "810e3c1a-af84-45e1-9508-a00c40523f7b", "metadata": {}, "source": [ "### Deel 2" ] }, { "cell_type": "code", "execution_count": 15, "id": "21a60b17-619f-426f-8617-5ff4352cca0c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "66027" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "total = 0\n", "for line in data:\n", " color_dict = {'red': [], 'green': [], 'blue': []}\n", " \n", " for pair in re.findall('(\\d+)\\W*(red|green|blue)', line):\n", " color_dict[pair[1]].append(int(pair[0]))\n", " total += max(color_dict['red']) * max(color_dict['green']) * max(color_dict['blue'])\n", "total" ] }, { "cell_type": "markdown", "id": "95831680-6f23-404b-97e6-0411c59f6bdf", "metadata": {}, "source": [ "## Puzzel 3" ] }, { "cell_type": "code", "execution_count": 104, "id": "3f70dc72-b4e4-4f65-87ac-d1222a01c8aa", "metadata": {}, "outputs": [], "source": [ "data = open('data/puzzle_3.txt', 'r').readlines()" ] }, { "cell_type": "code", "execution_count": 113, "id": "91a632d1-6262-4c28-bb17-45352c60c16e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "517021" ] }, "execution_count": 113, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data_list = [re.sub('\\n', '', line) for line in data]\n", "data_list = [re.sub('[^\\d\\.]', 'X', line) for line in data_list]\n", "total = 0\n", "for line_number, line in enumerate(data_list):\n", " matches = re.findall('\\d+', line)\n", " for number in matches:\n", " match = re.search(number, line)\n", " surrounding_string = \"\"\n", " start, end = match.span()\n", " if start > 0:\n", " start -= 1\n", " if end <= len(line):\n", " end += 1\n", " if line_number != 0:\n", " surrounding_string += data_list[line_number-1][start:end]\n", " surrounding_string += line[start:end]\n", " if line_number != len(data_list)-1:\n", " surrounding_string += data_list[line_number+1][start:end]\n", " if 'X' in surrounding_string:\n", " total += int(match.group())\n", " line = re.sub(match.group(), len(match.group())*'.', line, 1)\n", " match = re.search('\\d+', line) \n", "total" ] }, { "cell_type": "code", "execution_count": 138, "id": "4b239c25-3a43-459e-9669-aa9834571733", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "81296995" ] }, "execution_count": 138, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data_list = [re.sub('\\n', '', line) for line in data]\n", "asterisks = []\n", "numbers = []\n", "for line_number, line in enumerate(data_list):\n", " match = re.search('(\\*)|(\\d+)', line)\n", " while match is not None:\n", " x, y = match.span()\n", " if match.group() == '*':\n", " asterisks.append({'x_pos': x, 'line_number': line_number})\n", " else:\n", " numbers.append({'x_start':x, 'x_end': y, 'line_number': line_number, 'number': int(match.group())})\n", " line = re.sub('(\\*)|(\\d+)', len(match.group())*'.', line, 1)\n", " match = re.search('(\\*)|(\\d+)', line)\n", " \n", "for asterisk in asterisks:\n", " asterisk_numbers = []\n", " for number in numbers:\n", " if number['line_number'] == asterisk['line_number']:\n", " if number['x_end'] == asterisk['x_pos']:\n", " asterisk_numbers.append(number['number'])\n", " continue\n", " if number['x_start']-1 == asterisk['x_pos']:\n", " asterisk_numbers.append(number['number'])\n", " continue\n", " \n", " if (number['line_number']+1 == asterisk['line_number']) or (number['line_number']-1 == asterisk['line_number']):\n", " if asterisk['x_pos'] in [num for num in range(number['x_start']-1, number['x_end']+1)]:\n", " asterisk_numbers.append(number['number'])\n", "\n", " asterisk['numbers'] = asterisk_numbers\n", "total = 0\n", "for asterisk in asterisks:\n", " if len(asterisk['numbers']) == 2:\n", " total+= asterisk['numbers'][0] * asterisk['numbers'][1]\n", "total" ] }, { "cell_type": "markdown", "id": "db726345-15cd-4692-9d98-a8d3a28adfeb", "metadata": {}, "source": [ "## Puzzel 4" ] }, { "cell_type": "markdown", "id": "42c8bc93-34b9-4722-850a-bc4c15212fd8", "metadata": {}, "source": [ "### Deel 1" ] }, { "cell_type": "code", "execution_count": 2, "id": "2cbabb08-e696-4466-8963-844ec7d8fc15", "metadata": {}, "outputs": [], "source": [ "data = open('data/puzzle_4.txt', 'r').readlines()" ] }, { "cell_type": "code", "execution_count": 19, "id": "813183a3-31df-4cb2-a4f4-cbb0db517cb2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "21568\n" ] } ], "source": [ "# initiating output variable\n", "total = 0\n", "for line in data:\n", " # Cleaning identifier as it is not necessary\n", " line_number_part = line.split(':')[1]\n", "\n", " # Removing the \\n \n", " line_number_part = re.sub('\\n', '',line_number_part)\n", "\n", " # Creating a set with winning numbers and with owned numbers\n", " winning_numbers, owned_numbers = line_number_part.split('|')\n", "\n", " # Getting the seperate numbers\n", " winning_numbers = re.findall('(\\d+)', winning_numbers)\n", " owned_numbers = re.findall('(\\d+)', owned_numbers)\n", "\n", " # Converting to a set to prepare for intersect\n", " winning_set = set(winning_numbers)\n", " owned_set = set(owned_numbers)\n", "\n", " # Only numbers that are both owned and winning will be left\n", " winning_numbers_owned = winning_set.intersection(owned_set)\n", "\n", " # Get the number of matches\n", " matched_number_count = len(winning_numbers_owned)\n", "\n", " # If there are no matches, we add nothing to total, so we check for zero matches\n", " if matched_number_count > 0:\n", " # We then add to the total 2 to the power of the total number of matches minus one, as we start at 1 instead of 2 and 2^0 is 1 \n", " total += 2**(matched_number_count-1)\n", "print(total)" ] }, { "cell_type": "markdown", "id": "9d818873-9540-4de8-881a-620c02ddefca", "metadata": {}, "source": [ "### Deel 2" ] }, { "cell_type": "code", "execution_count": 23, "id": "64ac3677-aa84-4059-981a-857632b827c8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11827296\n" ] } ], "source": [ "# initiating output variable\n", "total = 0\n", "winning_numbers_on_card = []\n", "card_numbers = []\n", "copies_of_card = []\n", "for line in data:\n", " # Cleaning identifier\n", " card_identifier_part, line_number_part = line.split(':')\n", " identifier = int(re.search('\\d+', card_identifier_part).group())\n", "\n", " # adding to the list\n", " card_numbers.append(identifier)\n", "\n", " # Also adding a 1 to the owned cards list\n", " copies_of_card.append(1)\n", "\n", " # Removing the \\n \n", " line_number_part = re.sub('\\n', '',line_number_part)\n", "\n", " # Creating a set with winning numbers and with owned numbers\n", " winning_numbers, owned_numbers = line_number_part.split('|')\n", "\n", " # Getting the seperate numbers\n", " winning_numbers = re.findall('(\\d+)', winning_numbers)\n", " owned_numbers = re.findall('(\\d+)', owned_numbers)\n", "\n", " # Converting to a set to prepare for intersect\n", " winning_set = set(winning_numbers)\n", " owned_set = set(owned_numbers)\n", "\n", " # Only numbers that are both owned and winning will be left\n", " winning_numbers_owned = winning_set.intersection(owned_set)\n", "\n", " # Get the number of matches\n", " matched_number_count = len(winning_numbers_owned)\n", "\n", " # Add to card info list\n", " winning_numbers_on_card.append(matched_number_count)\n", "\n", "\n", "# Just simulating the rounds, if a card has winining numbers, loop over a range and add that loop variable to the card number\n", "# if the card number exists, we simply add the number of copies of the current card to that card\n", "# etc. \n", "for i, card_id in enumerate(card_numbers):\n", " winning_numbers = winning_numbers_on_card[i]\n", " for number in range(1, winning_numbers+1):\n", " if (card_id+number) in card_numbers:\n", " id_to_add_to = card_numbers.index(card_id+number)\n", " copies_of_card[id_to_add_to] += copies_of_card[i]\n", "\n", "# just sum the total cards at the end\n", "print(sum(copies_of_card))\n", " \n", " \n", " " ] }, { "cell_type": "markdown", "id": "bdaf4568-5996-493b-9d9b-398b5e16f522", "metadata": {}, "source": [ "# AANSCHOUW!!!!!\n", "Het wonder, het fantastischste ding ooit, oneliners" ] }, { "cell_type": "code", "execution_count": 302, "id": "091f006e-838e-418b-8282-610cc6fadccc", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "21568" ] }, "execution_count": 302, "metadata": {}, "output_type": "execute_result" } ], "source": [ "reduce(lambda total, multipliers: (total + 2**(multipliers-1) if (multipliers > 0) else total) ,map(lambda numbers: len(numbers)-len(set(numbers)), [re.findall('(?:(\\d+)\\s|\\n)', line) for line in open('data/puzzle_4.txt')]), 0)" ] }, { "cell_type": "code", "execution_count": 400, "id": "cdbdddfb-c0e4-4f9b-8b6c-4dd561c6236a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "11827296" ] }, "execution_count": 400, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum([y for (x,y) in reduce(lambda total, cards: total + [(cards[0], 1)] + [(card, 1+sum([total_card[1] for total_card in total if total_card[0] == cards[0]])) for card in cards[1]], enumerate([j+1+i for j in range(len(re.findall(r'(?:\\b(\\d+)\\s)(?=.*\\s\\1\\b)', line)))] for i, line in enumerate(open('data/puzzle_4.txt'))), [])])" ] }, { "cell_type": "markdown", "id": "5c0477b9-70f7-4cab-abee-ff843ede5b9c", "metadata": {}, "source": [ "## Puzzel 5" ] }, { "cell_type": "markdown", "id": "72c6c580-c46f-40da-90f7-f9bb4a3ba5e7", "metadata": {}, "source": [ "### Deel 1" ] }, { "cell_type": "code", "execution_count": 45, "id": "b638e651-ce5f-47af-baa2-b6baa71ccccf", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3871578677, 1724133724, 199602917, 2982314302, 595680226, 692431340, 2899305373, 2926286942, 4220409748, 2324727144, 2504054106, 2942258417, 1481150454, 1479468889, 2022824054, 4001340211, 3089202785]\n" ] }, { "data": { "text/plain": [ "199602917" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data = open('data/puzzle_5.txt','r').readlines()\n", "seeds = [int(seed) for seed in re.findall(r'\\d+', data[0])]\n", "\n", "seed_maps = []\n", "map_names = []\n", "mapping = []\n", "for line in data[1:]:\n", " if 'map' in line:\n", " mapping = []\n", " map_names.append(line)\n", " if line == '\\n':\n", " seed_maps.append(mapping)\n", " ints = [int(value) for value in re.findall(r'\\b(\\d+)', line)]\n", " if len(ints) > 0:\n", " mapping.append(ints)\n", "seed_maps.append(mapping)\n", "\n", "for mapping in seed_maps:\n", " if len(mapping) < 1:\n", " continue\n", " new_seeds = []\n", " for map_row in mapping:\n", " for seed in seeds:\n", " if (map_row[1]+map_row[2]) > seed >= map_row[1]:\n", " new_seeds.append(seed+map_row[0]-map_row[1])\n", " seeds = new_seeds\n", "print(seeds)\n", "min(seeds)" ] }, { "cell_type": "markdown", "id": "58230f2e-b277-408b-8c47-91297109e125", "metadata": {}, "source": [ "## Deel 2" ] }, { "cell_type": "code", "execution_count": 12, "id": "3d07272a-6d4e-476d-b321-0639b8433bae", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2254686" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data = open('data/puzzle_5.txt','r').readlines()\n", "seeds = [{'start': int(x), 'end': int(x) + int(y)} for (x,y) in re.findall(r'(?:(\\d+)\\s(\\d+))', data[0])]\n", "seed_maps = []\n", "map_names = []\n", "mapping = []\n", "for line in data[1:]:\n", " if 'map' in line:\n", " mapping = []\n", " map_names.append(line)\n", " if line == '\\n':\n", " if len(mapping) > 0:\n", " seed_maps.append(mapping)\n", " ints = [int(value) for value in re.findall(r'\\b(\\d+)', line)]\n", " if len(ints) > 0:\n", " mapping.append({'start': ints[1], 'end': ints[1]+ints[2], 'change': ints[0] - ints[1]})\n", "seed_maps.append(mapping)\n", "for seed_map in seed_maps:\n", " new_seeds = []\n", " for seed in seeds:\n", " bounds = [(seed['start'], 0), (seed['end'], 0)]\n", " for row in seed_map:\n", " if (row['start'] >= seed['end']) or (row['end'] <= seed['start']):\n", " continue\n", " if row['start'] <= seed['start']:\n", " bounds.append((seed['start'], row['change']))\n", " else:\n", " bounds.append((row['start'], row['change']))\n", " if row['end'] < seed['end']:\n", " bounds.append((row['end'], 0))\n", " bounds.sort(key=lambda x: x[0])\n", " for i in range(len(bounds)-1):\n", " lower_bound = bounds[i]\n", " upper_bound = bounds[i+1]\n", " if lower_bound[0] != lower_bound[1]:\n", " new_seeds.append({'start': lower_bound[0]+lower_bound[1], 'end': upper_bound[0]+lower_bound[1]})\n", " seeds = new_seeds\n", "min([seed['start'] for seed in seeds])" ] }, { "cell_type": "markdown", "id": "30d277d2-13e8-45d6-87da-ef02fa3d9779", "metadata": {}, "source": [ "## Puzzel 6" ] }, { "cell_type": "markdown", "id": "68cefad3-f476-4a7e-8ea2-93affd97daf6", "metadata": {}, "source": [ "## Deel 1" ] }, { "cell_type": "code", "execution_count": 7, "id": "75e6d50f-7c27-4aed-b948-f819d9347ab1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[358, 1054, 1807, 1080] [46, 68, 98, 66]\n" ] } ], "source": [ "data = open('data/puzzle_6.txt', 'r').readlines()\n", "times = [int(time) for time in re.findall(r'(\\d+)', data[0])]\n", "distances = [int(distance) for distance in re.findall(r'(\\d+)', data[1])]" ] }, { "cell_type": "code", "execution_count": 9, "id": "7213a72f-3421-43b2-afff-3b959f1d8380", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "138915" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "total_wins = []\n", "for time, distance in zip(times, distances):\n", " wins = 0\n", " for time_pressed in range(0, time+1):\n", " distance_travelled = time_pressed * (time-time_pressed)\n", " if distance_travelled > distance:\n", " wins += 1\n", " total_wins.append(wins)\n", "score = 1\n", "for win in total_wins:\n", " score = score*win\n", "score\n", " " ] }, { "cell_type": "markdown", "id": "efa4bdfd-636d-4d55-a4a1-9a4a4d300ab2", "metadata": {}, "source": [ "## Deel 2" ] }, { "cell_type": "code", "execution_count": 25, "id": "bf365352-52df-4495-a685-27595ff908fe", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9674509.498754364 37015356.50124563\n" ] }, { "data": { "text/plain": [ "27340847" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "time = [time for time in re.findall(r'(\\d+)', data[0])]\n", "time = int(''.join(time))\n", "distance = [distance for distance in re.findall(r'(\\d+)', data[1])]\n", "distance = int(''.join(distance))\n", "\n", "\n", "discriminant = (time**2) - (4 * distance)\n", "x0 = ((-time) + np.sqrt(discriminant))/-2\n", "x1 = ((-time) - np.sqrt(discriminant))/-2\n", "print(x0, x1)\n", "round(x1) - round(x0)-1" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.13" } }, "nbformat": 4, "nbformat_minor": 5 }