From b01db572f7d07be320a68b271ed3326a3502a49c Mon Sep 17 00:00:00 2001 From: <> Date: Thu, 28 Dec 2023 20:29:32 +0000 Subject: [PATCH] Deployed 1e9885e with MkDocs version: 1.5.3 --- 2015/index.html | 60 +++++++++++++++++++++++++++++++++++++++ 2018/index.html | 6 ++-- 2019/index.html | 4 +-- 2021/index.html | 2 +- 2022/index.html | 2 +- 2023/index.html | 2 +- 404.html | 2 +- index.html | 2 +- search/search_index.json | 2 +- sitemap.xml.gz | Bin 127 -> 127 bytes 10 files changed, 71 insertions(+), 11 deletions(-) create mode 100644 2015/index.html diff --git a/2015/index.html b/2015/index.html new file mode 100644 index 0000000..d1dd842 --- /dev/null +++ b/2015/index.html @@ -0,0 +1,60 @@ + Year 2015 - advent-of-code
Skip to content

Advent of Code 2015

Day 01
 1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
+10
+11
with open("day01_input.txt", "r") as f:
+    s = f.read()
+
+floor = 0
+for c in s:
+    if c == "(":
+        floor += 1
+    elif c == ")":
+        floor -= 1
+
+print(floor)
+
 1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
+10
+11
+12
+13
+14
with open("day01_input.txt", "r") as f:
+    s = f.read()
+
+floor = 0
+for i in range(len(s)):
+    c = s[i]
+    if c == "(":
+        floor += 1
+    elif c == ")":
+        floor -= 1
+    if floor == -1:
+        break
+
+print(i + 1)
+
\ No newline at end of file diff --git a/2018/index.html b/2018/index.html index 7d9f785..ea2d7ed 100644 --- a/2018/index.html +++ b/2018/index.html @@ -1,4 +1,4 @@ - Year 2018 - advent-of-code
Skip to content

Advent of Code 2018

Day 01
1
+                  

Advent of Code 2018

Day 01
1
 2
 3
 4
with open("day01_input.txt", "r") as f:
     changes = [int(i) for i in f.read().splitlines()]
 
 print(sum(changes))
-
\ No newline at end of file +
\ No newline at end of file diff --git a/2019/index.html b/2019/index.html index d09073a..0a47bc2 100644 --- a/2019/index.html +++ b/2019/index.html @@ -9,7 +9,7 @@ body[data-md-color-scheme="slate"] .gdesc-inner { background: var(--md-default-bg-color);} body[data-md-color-scheme="slate"] .gslide-title { color: var(--md-default-fg-color);} body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);} -
Skip to content

Advent of Code 2019

Day 01
1
+                  

Advent of Code 2019

Day 01
1
 2
 3
 4
@@ -18,4 +18,4 @@
 
 fuels = [mass // 3 - 2 for mass in data]
 print(sum(fuels))
-
\ No newline at end of file +
\ No newline at end of file diff --git a/2021/index.html b/2021/index.html index 17e43de..bf58326 100644 --- a/2021/index.html +++ b/2021/index.html @@ -9,7 +9,7 @@ body[data-md-color-scheme="slate"] .gdesc-inner { background: var(--md-default-bg-color);} body[data-md-color-scheme="slate"] .gslide-title { color: var(--md-default-fg-color);} body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);} -
Skip to content

Advent of Code 2021

Day 01
1
+                  

Advent of Code 2021

Day 01
1
 2
 3
 4
diff --git a/2022/index.html b/2022/index.html
index b801ab3..3286e13 100644
--- a/2022/index.html
+++ b/2022/index.html
@@ -9,7 +9,7 @@
             body[data-md-color-scheme="slate"] .gdesc-inner { background: var(--md-default-bg-color);}
             body[data-md-color-scheme="slate"] .gslide-title { color: var(--md-default-fg-color);}
             body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);}
-                  

Advent of Code 2022

Day 01
 1
+                  

Advent of Code 2022

Day 01
 1
  2
  3
  4
diff --git a/2023/index.html b/2023/index.html
index e54c24b..8e51e05 100644
--- a/2023/index.html
+++ b/2023/index.html
@@ -9,7 +9,7 @@
             body[data-md-color-scheme="slate"] .gdesc-inner { background: var(--md-default-bg-color);}
             body[data-md-color-scheme="slate"] .gslide-title { color: var(--md-default-fg-color);}
             body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);}
-                  

Advent of Code 2023

Day 01
1
+                  

Advent of Code 2023

Day 01
1
 2
 3
 4
diff --git a/404.html b/404.html
index 7d851da..182718b 100644
--- a/404.html
+++ b/404.html
@@ -1 +1 @@
- advent-of-code     

404 - Not found

\ No newline at end of file + advent-of-code

404 - Not found

\ No newline at end of file diff --git a/index.html b/index.html index 7ac366d..69e9d18 100644 --- a/index.html +++ b/index.html @@ -9,4 +9,4 @@ body[data-md-color-scheme="slate"] .gdesc-inner { background: var(--md-default-bg-color);} body[data-md-color-scheme="slate"] .gslide-title { color: var(--md-default-fg-color);} body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);} -
\ No newline at end of file +
\ No newline at end of file diff --git a/search/search_index.json b/search/search_index.json index 8882749..9d659f0 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Home","text":""},{"location":"#advent-of-code","title":"Advent of Code","text":"
  • 2023
  • 2022
  • 2021
  • 2019
  • 2018
"},{"location":"2018/","title":"Advent of Code 2018","text":"Day 01 Part 1
with open(\"day01_input.txt\", \"r\") as f:\n    changes = [int(i) for i in f.read().splitlines()]\n\nprint(sum(changes))\n
"},{"location":"2019/","title":"Advent of Code 2019","text":"Day 01 Part 1
with open(\"day01_input.txt\", \"r\") as f:\n    data = [int(i) for i in f.read().splitlines()]\n\nfuels = [mass // 3 - 2 for mass in data]\nprint(sum(fuels))\n
"},{"location":"2021/","title":"Advent of Code 2021","text":"Day 01 Part 1Part 2
with open(\"day01_input.txt\", \"r\") as f:\n    data = [int(i) for i in f.read().splitlines()]\n\ncount = 0\nfor i in range(1, len(data)):\n    if data[i] > data[i - 1]:\n        count += 1\n\nprint(count)\n
with open(\"day01_input.txt\", \"r\") as f:\n    data = [int(i) for i in f.read().splitlines()]\n\nthree_measurement_data = []\nfor i in range(2, len(data)):\n    three_measurement_data.append(sum(data[i - 2 : i + 1]))\n\ncount = 0\nfor i in range(1, len(three_measurement_data)):\n    if three_measurement_data[i] > three_measurement_data[i - 1]:\n        count += 1\n\nprint(count)\n
Day 02 Part 1Part 2
with open(\"day02_input.txt\", \"r\") as f:\n    data = [cmd.split() for cmd in f.read().splitlines()]\n\nhorizontal_position, depth = 0, 0\n\nfor action, value in data:\n    value = int(value)\n    if action == \"forward\":\n        horizontal_position += value\n    elif action == \"up\":\n        depth -= value\n    elif action == \"down\":\n        depth += value\n\nprint(horizontal_position, depth)\n\nprint(horizontal_position * depth)\n
with open(\"day02_input.txt\", \"r\") as f:\n    data = [cmd.split() for cmd in f.read().splitlines()]\n\nhorizontal_position, depth, aim = 0, 0, 0\n\nfor action, value in data:\n    value = int(value)\n    if action == \"forward\":\n        horizontal_position += value\n        depth += aim * value\n    elif action == \"up\":\n        aim -= value\n    elif action == \"down\":\n        aim += value\n\n\nprint(horizontal_position, depth, aim)\n\nprint(horizontal_position * depth)\n
Day 03 Part 1Part 2
with open(\"day03_input.txt\", \"r\") as f:\n    data = f.read().splitlines()\n\ncols = len(data[0])\nrows = len(data)\n\ngamma_rate, epsilon_rate = \"\", \"\"\n\nfor col in range(cols):\n    ones = 0\n    for row in range(rows):\n        if data[row][col] == \"1\":\n            ones += 1\n\n    if ones > rows / 2:\n        gamma_rate += \"1\"\n        epsilon_rate += \"0\"\n    else:\n        gamma_rate += \"0\"\n        epsilon_rate += \"1\"\n\nprint(gamma_rate, epsilon_rate)\n\nprint(int(gamma_rate, 2) * int(epsilon_rate, 2))\n
with open(\"day03_input.txt\", \"r\") as f:\n    data = f.read().splitlines()\n\ncols = len(data[0])\n\noxygen_generator_rating, co2_scrubber_rating = \"\", \"\"\n\nselections = data[:]\nfor col in range(cols):\n    ones = 0\n    for row in selections:\n        if row[col] == \"1\":\n            ones += 1\n\n    if ones >= len(selections) / 2:\n        selections = [row for row in selections if row[col] == \"1\"]\n    else:\n        selections = [row for row in selections if row[col] == \"0\"]\n\n    if len(selections) == 1:\n        oxygen_generator_rating += selections[0]\n        break\n\nselections = data[:]\nfor col in range(cols):\n    ones = 0\n    for row in selections:\n        if row[col] == \"1\":\n            ones += 1\n\n    if ones < len(selections) / 2:\n        selections = [row for row in selections if row[col] == \"1\"]\n    else:\n        selections = [row for row in selections if row[col] == \"0\"]\n\n    if len(selections) == 1:\n        co2_scrubber_rating += selections[0]\n        break\n\n\nprint(oxygen_generator_rating, co2_scrubber_rating)\n\nprint(int(oxygen_generator_rating, 2) * int(co2_scrubber_rating, 2))\n
Day 04 Part 1Part 2
with open(\"day04_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\ndraws = lines[0].split(\",\")\n\n\nlines = [line for line in lines[1:] if line]\nboards = []\nfor i in range(0, len(lines) // 5):\n    boards.append([])\n    for j in range(5):\n        boards[i].append(lines[i * 5 + j].split())\n\n\nmarks = {}\nfor i in range(len(boards)):\n    marks[i] = {}\n    for row in range(5):\n        for col in range(5):\n            marks[i][boards[i][row][col]] = (row, col)\n\n\nwinning_locations = []\nfor row in range(5):\n    winning_locations.append([(row, col) for col in range(5)])\nfor col in range(5):\n    winning_locations.append([(row, col) for row in range(5)])\n\n\ndef wins(locations, winning_locations=winning_locations):\n    for winning_location in winning_locations:\n        if all(loc in locations for loc in winning_location):\n            return winning_location\n\n    return None\n\n\nplays = {}\nfor i in range(len(boards)):\n    plays[i] = []\n\nnum_plays = {}\nfor i in range(len(boards)):\n    count = 0\n    for draw in draws:\n        count += 1\n        if draw in marks[i]:\n            plays[i].append(marks[i][draw])\n\n        if wins(plays[i]):\n            num_plays[i] = count, len(plays[i])\n            break\n\n\nfastest_win = min(num_plays, key=lambda x: num_plays[x][0])\nprint(fastest_win)\n\n\nsum_unmarked = 0\nfor row in range(5):\n    for col in range(5):\n        if (row, col) not in plays[fastest_win]:\n            sum_unmarked += int(boards[fastest_win][row][col])\n\nrow, col = plays[fastest_win][-1]\nnum_call = int(boards[fastest_win][row][col])\n\n\nprint(sum_unmarked, num_call)\nprint(sum_unmarked * num_call)\n
with open(\"day04_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\ndraws = lines[0].split(\",\")\n\n\nlines = [line for line in lines[1:] if line]\nboards = []\nfor i in range(0, len(lines) // 5):\n    boards.append([])\n    for j in range(5):\n        boards[i].append(lines[i * 5 + j].split())\n\n\nmarks = {}\nfor i in range(len(boards)):\n    marks[i] = {}\n    for row in range(5):\n        for col in range(5):\n            marks[i][boards[i][row][col]] = (row, col)\n\n\nwinning_locations = []\nfor row in range(5):\n    winning_locations.append([(row, col) for col in range(5)])\nfor col in range(5):\n    winning_locations.append([(row, col) for row in range(5)])\n\n\ndef wins(locations, winning_locations=winning_locations):\n    for winning_location in winning_locations:\n        if all(loc in locations for loc in winning_location):\n            return winning_location\n\n    return None\n\n\nplays = {}\nfor i in range(len(boards)):\n    plays[i] = []\n\nnum_plays = {}\nfor i in range(len(boards)):\n    count = 0\n    for draw in draws:\n        count += 1\n        if draw in marks[i]:\n            plays[i].append(marks[i][draw])\n\n        if wins(plays[i]):\n            num_plays[i] = count, len(plays[i])\n            break\n\n\nlast_win = max(num_plays, key=lambda x: num_plays[x][0])\nprint(last_win)\n\n\nsum_unmarked = 0\nfor row in range(5):\n    for col in range(5):\n        if (row, col) not in plays[last_win]:\n            sum_unmarked += int(boards[last_win][row][col])\n\nrow, col = plays[last_win][-1]\nnum_call = int(boards[last_win][row][col])\n\n\nprint(sum_unmarked, num_call)\nprint(sum_unmarked * num_call)\n
Day 05 Part 1Part 2
with open(\"day05_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\nlines = [line.split(\" -> \") for line in lines]\nlines = [(tuple(line[0].split(\",\")), tuple(line[1].split(\",\"))) for line in lines]\nprint(len(lines))\n\nlines = [\n    ((int(coord1[0]), int(coord1[1])), (int(coord2[0]), int(coord2[1])))\n    for coord1, coord2 in lines\n    if coord1[0] == coord2[0] or coord1[1] == coord2[1]\n]\nprint(len(lines))\n\nfrom collections import Counter\n\ndiagram = Counter()\nfor coord1, coord2 in lines:\n    if coord1[0] == coord2[0]:\n        for i in range(min(coord1[1], coord2[1]), max(coord1[1], coord2[1]) + 1):\n            diagram[(coord1[0], i)] += 1\n    elif coord1[1] == coord2[1]:\n        for i in range(min(coord1[0], coord2[0]), max(coord1[0], coord2[0]) + 1):\n            diagram[(i, coord1[1])] += 1\n\nprint(len([i for i in diagram.values() if i > 1]))\n
with open(\"day05_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\nlines = [line.split(\" -> \") for line in lines]\nlines = [(tuple(line[0].split(\",\")), tuple(line[1].split(\",\"))) for line in lines]\nprint(len(lines))\n\nlines = [\n    ((int(coord1[0]), int(coord1[1])), (int(coord2[0]), int(coord2[1])))\n    for coord1, coord2 in lines\n]\n\nfrom collections import Counter\n\ndiagram = Counter()\nfor coord1, coord2 in lines:\n    if coord1[0] == coord2[0]:\n        for i in range(min(coord1[1], coord2[1]), max(coord1[1], coord2[1]) + 1):\n            diagram[(coord1[0], i)] += 1\n    elif coord1[1] == coord2[1]:\n        for i in range(min(coord1[0], coord2[0]), max(coord1[0], coord2[0]) + 1):\n            diagram[(i, coord1[1])] += 1\n    else:\n        step_x = -1 if coord1[0] - coord2[0] > 0 else 1\n        step_y = -1 if coord1[1] - coord2[1] > 0 else 1\n        for x, y in zip(\n            range(coord1[0], coord2[0] + (1 if step_x > 0 else -1), step_x),\n            range(coord1[1], coord2[1] + (1 if step_y > 0 else -1), step_y),\n        ):\n            diagram[(x, y)] += 1\n\nprint(len([i for i in diagram.values() if i > 1]))\n
Day 06 Part 1Part 2
with open(\"day06_input.txt\", \"r\") as f:\n    fish = [int(i) for i in f.read().strip().split(\",\")]\n\nprint(f\"Initial state: {fish}\")\n\nfor _ in range(80):\n    new_fish = []\n    for i in range(len(fish)):\n\n        fish[i] -= 1\n\n        if fish[i] < 0:\n            fish[i] = 6\n            new_fish.append(8)\n\n    fish.extend(new_fish)\n\n    print(f\"After {str(_+1):2s} day{'s' if _ else ''}: {fish}\")\n\nprint(len(fish))\n
with open(\"day06_input.txt\", \"r\") as f:\n    fish = [int(i) for i in f.read().strip().split(\",\")]\n\n\nfrom collections import Counter\n\nfish = Counter(fish)\nprint(fish)\n\nfor _ in range(256):\n    for i in range(-1, 9):\n        if i == 8:\n            fish[i] = fish[-1]\n        elif i != 6:\n            fish[i] = fish[i + 1]\n        else:\n            fish[i] = fish[-1] + fish[i + 1]\n\n\nprint(sum([v for k, v in fish.items() if k >= 0]))\n
Day 07 Part 1Part 2
with open(\"day07_input.txt\", \"r\") as f:\n    crabs = [int(i) for i in f.read().strip().split(\",\")]\n\nprint(len(crabs))\n\nfrom collections import Counter\n\ncrabs = Counter(crabs)\n\n\noutcome = {}\n\nfor key in crabs:\n    result = 0\n    for key2 in crabs:\n        result += abs(key2 - key) * crabs[key2]\n    outcome[key] = result\n\nmin_key = min(outcome, key=outcome.get)\nprint(min_key)\nprint(outcome[min_key])\n
with open(\"day07_input.txt\", \"r\") as f:\n    crabs = [int(i) for i in f.read().strip().split(\",\")]\n\nprint(len(crabs))\n\nfrom collections import Counter\n\ncrabs = Counter(crabs)\n\n\noutcome = {}\n\nfor key in range(0, max(crabs.keys()) + 1):\n    result = 0\n    for key2 in crabs:\n        result += sum(range(1, abs(key2 - key) + 1)) * crabs[key2]\n    outcome[key] = result\n\nmin_key = min(outcome, key=outcome.get)\nprint(min_key)\nprint(outcome[min_key])\n
Day 08 Part 1Part 2
with open(\"day08_input.txt\", \"r\") as f:\n    obs = [line.split(\" | \") for line in f.read().splitlines()]\n\ncount = 0\nfor o in obs:\n    output_values = o[1].split()\n    for output_value in output_values:\n        if len(output_value) in [2, 3, 4, 7]:\n            count += 1\n\nprint(count)\n
with open(\"day08_input.txt\", \"r\") as f:\n    obs = [line.split(\" | \") for line in f.read().splitlines()]\n\n\ndef _sorted(digit):\n    return \"\".join(sorted(digit))\n\n\ndef solve(digits):\n    mapping = {}\n    five_segs = []\n    six_segs = []\n\n    cf, bcdf, acf, abcdefg = None, None, None, None\n    for digit in digits:\n        if len(digit) == 2:\n            mapping[_sorted(digit)] = \"1\"\n            cf = digit\n        elif len(digit) == 3:\n            mapping[_sorted(digit)] = \"7\"\n            acf = digit\n        elif len(digit) == 4:\n            mapping[_sorted(digit)] = \"4\"\n            bcdf = digit\n        elif len(digit) == 7:\n            mapping[_sorted(digit)] = \"8\"\n            abcdefg = digit\n        elif len(digit) == 5:\n            five_segs.append(digit)\n        elif len(digit) == 6:\n            six_segs.append(digit)\n\n    bd = set(bcdf) - set(cf)\n    eg = set(abcdefg) - (set(cf) | set(bcdf) | set(acf))\n\n    for digit in six_segs:\n        _digit = set(digit)\n        if _digit >= bd and _digit >= eg:\n            mapping[_sorted(digit)] = \"6\"\n        elif _digit >= bd:\n            mapping[_sorted(digit)] = \"9\"\n        elif _digit >= eg:\n            mapping[_sorted(digit)] = \"0\"\n\n    for digit in five_segs:\n        _digit = set(digit)\n        if _digit >= bd:\n            mapping[_sorted(digit)] = \"5\"\n        elif _digit >= eg:\n            mapping[_sorted(digit)] = \"2\"\n        else:\n            mapping[_sorted(digit)] = \"3\"\n\n    return mapping\n\n\ncount = 0\nfor o in obs:\n    output_values = o[1].split()\n    digits = o[0].split()\n    mapping = solve(digits)\n    value = \"\"\n    for digit in output_values:\n        value += mapping[_sorted(digit)]\n\n    count += int(value)\n\nprint(count)\n
Day 09 Part 1Part 2
with open(\"day09_input.txt\", \"r\") as f:\n    obs = [[int(i) for i in line] for line in f.read().splitlines()]\n\n\nlow_points = []\nfor i in range(0, len(obs)):\n    for j in range(0, len(obs[i])):\n        to_compare = []\n        if i > 0:\n            to_compare.append(obs[i - 1][j])\n        if i < len(obs) - 1:\n            to_compare.append(obs[i + 1][j])\n        if j > 0:\n            to_compare.append(obs[i][j - 1])\n        if j < len(obs[i]) - 1:\n            to_compare.append(obs[i][j + 1])\n\n        if all(obs[i][j] < x for x in to_compare):\n            low_points.append(obs[i][j])\n\n\nprint(sum(low_points) + len(low_points))\n
with open(\"day09_input.txt\", \"r\") as f:\n    obs = [[int(i) for i in line] for line in f.read().splitlines()]\n\n\nlow_points = []\nfor i in range(0, len(obs)):\n    for j in range(0, len(obs[i])):\n        to_compare = []\n        if i > 0:\n            to_compare.append(obs[i - 1][j])\n        if i < len(obs) - 1:\n            to_compare.append(obs[i + 1][j])\n        if j > 0:\n            to_compare.append(obs[i][j - 1])\n        if j < len(obs[i]) - 1:\n            to_compare.append(obs[i][j + 1])\n\n        if all(obs[i][j] < x for x in to_compare):\n            low_points.append((i, j))\n\nbasin_sizes = []\n\n\ndef find_basin(i, j, points):\n    points.append((i, j))\n\n    up = i\n    while True:\n        if up > 0:\n            if obs[up - 1][j] > obs[up][j] and obs[up - 1][j] < 9:\n                find_basin(up - 1, j, points)\n                up -= 1\n            else:\n                break\n        else:\n            break\n\n    down = i\n    while True:\n        if down < len(obs) - 1:\n            if obs[down + 1][j] > obs[down][j] and obs[down + 1][j] < 9:\n                find_basin(down + 1, j, points)\n                down += 1\n            else:\n                break\n        else:\n            break\n\n    left = j\n    while True:\n        if left > 0:\n            if obs[i][left - 1] > obs[i][left] and obs[i][left - 1] < 9:\n                find_basin(i, left - 1, points)\n                left -= 1\n            else:\n                break\n        else:\n            break\n\n    right = j\n    while True:\n        if right < len(obs[i]) - 1:\n            if obs[i][right + 1] > obs[i][right] and obs[i][right + 1] < 9:\n                find_basin(i, right + 1, points)\n                right += 1\n            else:\n                break\n        else:\n            break\n\n\nfor i, j in low_points:\n    points = []\n    find_basin(i, j, points)\n    basin_sizes.append(len(set(points)))\n\nimport functools\n\nprint(functools.reduce(lambda x, y: x * y, sorted(basin_sizes)[-3:]))\n
Day 10 Part 1Part 2
with open(\"day10_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\nmapping = {\n    \")\": 3,\n    \"]\": 57,\n    \"}\": 1197,\n    \">\": 25137,\n}\n\nmatch = {\n    \")\": \"(\",\n    \"]\": \"[\",\n    \"}\": \"{\",\n    \">\": \"<\",\n}\n\n\ndef check(line):\n    stack = []\n    for c in line:\n        if c in match.values():\n            stack.append(c)\n        elif c in match.keys():\n            if len(stack) == 0:\n                return mapping[c]\n            last = stack.pop()\n            if last != match[c]:\n                return mapping[c]\n\n    return 0\n\n\nprint(sum(check(line) for line in lines))\n
with open(\"day10_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\nmapping = {\n    \"(\": 1,\n    \"[\": 2,\n    \"{\": 3,\n    \"<\": 4,\n}\n\nmatch = {\n    \")\": \"(\",\n    \"]\": \"[\",\n    \"}\": \"{\",\n    \">\": \"<\",\n}\n\n\ndef check(line):\n    stack = []\n    for c in line:\n        if c in match.values():\n            stack.append(c)\n        elif c in match.keys():\n            if len(stack) == 0:\n                return 0\n            last = stack.pop()\n            if last != match[c]:\n                return 0\n\n    if len(stack) == 0:\n        return 0\n\n    score = 0\n    while len(stack) > 0:\n        last = stack.pop()\n        score *= 5\n        score += mapping[last]\n\n    return score\n\n\nscores = [check(line) for line in lines]\nscores = [s for s in scores if s > 0]\nprint(len(scores))\nprint(sorted(scores)[len(scores) // 2])\n
Day 11 Part 1Part 2
with open(\"day11_input.txt\", \"r\") as f:\n    obs = [[int(i) for i in line] for line in f.read().splitlines()]\n\n\ndef increase(obs):\n    for i in range(len(obs)):\n        for j in range(len(obs[i])):\n            obs[i][j] += 1\n\n\ndef has_flash(obs):\n    locations = []\n    for i in range(len(obs)):\n        for j in range(len(obs[i])):\n            if obs[i][j] > 9:\n                locations.append((i, j))\n    return locations\n\n\ndef display(obs):\n    for i in range(len(obs)):\n        print(\"\".join([str(i) for i in obs[i]]))\n\n\nfrom collections import Counter\n\nprint(\"Before any steps:\")\ndisplay(obs)\nprint()\n\ncount = 0\nfor s in range(100):\n    increase(obs)\n\n    flashes = set()\n    while True:\n        locations = has_flash(obs)\n        flashes.update(locations)\n\n        if locations:\n            c = Counter()\n            for i, j in locations:\n                obs[i][j] = 0\n                if i > 0:\n                    c[(i - 1, j)] += 1\n                    if j > 0:\n                        c[(i - 1, j - 1)] += 1\n                    if j < len(obs[i]) - 1:\n                        c[(i - 1, j + 1)] += 1\n                if i < len(obs) - 1:\n                    c[(i + 1, j)] += 1\n                    if j > 0:\n                        c[(i + 1, j - 1)] += 1\n                    if j < len(obs[i]) - 1:\n                        c[(i + 1, j + 1)] += 1\n                if j > 0:\n                    c[(i, j - 1)] += 1\n                if j < len(obs[i]) - 1:\n                    c[(i, j + 1)] += 1\n            for i, j in c:\n                if (i, j) not in flashes:\n                    obs[i][j] += c[(i, j)]\n            if c:\n                continue\n        break\n\n    print(f\"After step {s+1}:\")\n    display(obs)\n    print(f\"Flashes: {len(flashes)}\")\n    print()\n\n    count += len(flashes)\n\nprint(f\"Total flashes: {count}\")\n
with open(\"day11_input.txt\", \"r\") as f:\n    obs = [[int(i) for i in line] for line in f.read().splitlines()]\n\n\ndef increase(obs):\n    for i in range(len(obs)):\n        for j in range(len(obs[i])):\n            obs[i][j] += 1\n\n\ndef has_flash(obs):\n    locations = []\n    for i in range(len(obs)):\n        for j in range(len(obs[i])):\n            if obs[i][j] > 9:\n                locations.append((i, j))\n    return locations\n\n\ndef display(obs):\n    for i in range(len(obs)):\n        print(\"\".join([str(i) for i in obs[i]]))\n\n\nfrom collections import Counter\n\n\nprint(\"Before any steps:\")\ndisplay(obs)\nprint()\n\n\ncount = 0\noctopuses = sum([len(obs[i]) for i in range(len(obs))])\nwhile True:\n    increase(obs)\n\n    flashes = set()\n    while True:\n        locations = has_flash(obs)\n        flashes.update(locations)\n\n        if locations:\n            c = Counter()\n            for i, j in locations:\n                obs[i][j] = 0\n                if i > 0:\n                    c[(i - 1, j)] += 1\n                    if j > 0:\n                        c[(i - 1, j - 1)] += 1\n                    if j < len(obs[i]) - 1:\n                        c[(i - 1, j + 1)] += 1\n                if i < len(obs) - 1:\n                    c[(i + 1, j)] += 1\n                    if j > 0:\n                        c[(i + 1, j - 1)] += 1\n                    if j < len(obs[i]) - 1:\n                        c[(i + 1, j + 1)] += 1\n                if j > 0:\n                    c[(i, j - 1)] += 1\n                if j < len(obs[i]) - 1:\n                    c[(i, j + 1)] += 1\n            for i, j in c:\n                if (i, j) not in flashes:\n                    obs[i][j] += c[(i, j)]\n            if c:\n                continue\n        break\n\n    print(f\"After step {count+1}:\")\n    display(obs)\n    print(f\"Flashes: {len(flashes)}\")\n    print()\n\n    count += 1\n    if len(flashes) == octopuses:\n        break\n\nprint(f\"Total steps: {count}\")\n
Day 12 Part 1Part 2
with open(\"day12_input.txt\", \"r\") as f:\n    segs = f.read().splitlines()\n\n\ngraph = {}\nfor seg in segs:\n    node1, node2 = seg.split(\"-\")\n    if node1 not in graph:\n        graph[node1] = [node2]\n    else:\n        graph[node1].append(node2)\n\n    if node2 not in graph:\n        graph[node2] = [node1]\n    else:\n        graph[node2].append(node1)\n\nfrom pprint import pprint\n\npprint(graph)\n\n\npaths = []\n\n\ndef breadth_first_search(graph, start, end, path=[]):\n    path = path + [start]\n    if start == end:\n        paths.append(path)\n    if start not in graph:\n        return None\n    for node in graph[start]:\n        if node not in path or node.isupper():\n            newpath = breadth_first_search(graph, node, end, path)\n            if newpath:\n                paths.append(newpath)\n    return None\n\n\nbreadth_first_search(graph, \"start\", \"end\")\n\nfor path in paths:\n    print(\",\".join(path))\n\nprint(len(paths))\n
with open(\"day12_input.txt\", \"r\") as f:\n    segs = f.read().splitlines()\n\n\ngraph = {}\nfor seg in segs:\n    node1, node2 = seg.split(\"-\")\n    if node1 not in graph:\n        graph[node1] = [node2]\n    else:\n        graph[node1].append(node2)\n\n    if node2 not in graph:\n        graph[node2] = [node1]\n    else:\n        graph[node2].append(node1)\n\nfrom pprint import pprint\n\npprint(graph)\n\n\npaths = []\n\n\ndef remaining(path, node):\n    others = [\n        n for n in path if n != node and n.islower() and n not in [\"start\", \"end\"]\n    ]\n\n    return all(path.count(n) <= 1 for n in others)\n\n\ndef breadth_first_search(graph, start, end, path=[]):\n\n    path = path + [start]\n    if start == end:\n        paths.append(path)\n    if start not in graph:\n        return None\n    for node in graph[start]:\n        if (\n            node not in path\n            or node.isupper()\n            or (\n                node not in [\"start\", \"end\"]\n                and node.islower()\n                and path.count(node) < 2\n                and remaining(path, node)\n            )\n        ):\n            newpath = breadth_first_search(graph, node, end, path)\n            if newpath:\n                paths.append(newpath)\n    return None\n\n\nbreadth_first_search(graph, \"start\", \"end\")\n\nfor path in paths:\n    print(\",\".join(path))\n\nprint(len(paths))\n
Day 13 Part 1Part 2
with open(\"day13_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\ndots = []\nactions = []\nfor line in lines:\n    if not line:\n        continue\n    if \",\" in line:\n        x, y = line.split(\",\")\n        dots.append((int(x), int(y)))\n    else:\n        actions.append(line.split()[-1].split(\"=\"))\n\nprevious = dots[:]\n\nfor axis, value in actions:\n    result = []\n    value = int(value)\n    if axis == \"x\":\n        for dot in previous:\n            if dot[0] < value:\n                result.append((dot[0], dot[1]))\n            else:\n                result.append((2 * value - dot[0], dot[1]))\n\n    elif axis == \"y\":\n        for dot in previous:\n            if dot[1] < value:\n                result.append((dot[0], dot[1]))\n            else:\n                result.append((dot[0], 2 * value - dot[1]))\n\n    print(len(set(result)))\n\n    previous = result[:]\n
with open(\"day13_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\ndots = []\nactions = []\nfor line in lines:\n    if not line:\n        continue\n    if \",\" in line:\n        x, y = line.split(\",\")\n        dots.append((int(x), int(y)))\n    else:\n        actions.append(line.split()[-1].split(\"=\"))\n\nprevious = dots[:]\n\nfor axis, value in actions:\n    result = []\n    value = int(value)\n    if axis == \"x\":\n        for dot in previous:\n            if dot[0] < value:\n                result.append((dot[0], dot[1]))\n            else:\n                result.append((2 * value - dot[0], dot[1]))\n\n    elif axis == \"y\":\n        for dot in previous:\n            if dot[1] < value:\n                result.append((dot[0], dot[1]))\n            else:\n                result.append((dot[0], 2 * value - dot[1]))\n\n    print(len(set(result)))\n\n    previous = result[:]\n\nmax_x = max(result, key=lambda x: x[0])[0]\nmax_y = max(result, key=lambda x: x[1])[1]\nprint(max_x, max_y)\n\nfor y in range(max_y + 1):\n    for x in range(max_x + 1):\n        if (x, y) in result:\n            print(\"#\", end=\"\")\n        else:\n            print(\" \", end=\"\")\n    print()\n\nfrom PIL import Image\n\nimg = Image.new(\"RGB\", (max_x + 1, max_y + 1), \"black\")\npixels = img.load()\nfor dot in set(result):\n    pixels[dot[0], dot[1]] = (255, 255, 255)\nimg.show()\n
Day 14 Part 1Part 2
with open(\"day14_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\ntemplate = None\npairs = []\nfor line in lines:\n    if not line:\n        continue\n    if \" -> \" in line:\n        pairs.append(line.split(\" -> \"))\n    else:\n        template = line\n\nprint(f\"Template: {template}\")\n\nfor i in range(10):\n    segs = [template[j : j + 2] for j in range(0, len(template) - 1)]\n\n    for k in range(len(segs)):\n        for pair in pairs:\n            if segs[k] == pair[0]:\n                segs[k] = pair[0][0] + pair[1] + pair[0][1]\n\n    template = segs[0]\n    for seg in segs[1:]:\n        template += seg[-2:]\n\n    print(f\"After step {i+1}: {template}\")\n\nfrom collections import Counter\n\ncounts = Counter(template).most_common()\n\nprint(counts[0][1] - counts[-1][1])\n
with open(\"day14_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\ntemplate = None\npairs = []\nfor line in lines:\n    if not line:\n        continue\n    if \" -> \" in line:\n        pairs.append(line.split(\" -> \"))\n    else:\n        template = line\n\nprint(f\"Template: {template}\")\nsegs = [template[j : j + 2] for j in range(0, len(template) - 1)]\n\nfrom collections import Counter\n\ncounts = Counter(segs)\n\n\nfor i in range(40):\n    result = Counter()\n    for key in counts:\n        for pair in pairs:\n            if key == pair[0]:\n                result[key[0] + pair[1]] += counts[key]\n                result[pair[1] + key[1]] += counts[pair[0]]\n\n    counts = result\n\n\nchars = Counter()\nchars[template[0]] += 1\n\nfor key, value in counts.items():\n    chars[key[1]] += value\n\nchars = chars.most_common()\nprint(chars)\nprint(chars[0][1] - chars[-1][1])\n
Day 15 Part 1Part 2
with open(\"day15_input.txt\", \"r\") as f:\n    risks = [[int(d) for d in line] for line in f.read().splitlines()]\n\nrows, cols = len(risks), len(risks[0])\n\n# reference: https://stackabuse.com/dijkstras-algorithm-in-python/\n\nfrom queue import PriorityQueue\n\n\nclass Graph:\n    def __init__(self, num_of_vertices):\n        self.v = num_of_vertices\n        self.edges = [\n            [-1 for i in range(num_of_vertices)] for j in range(num_of_vertices)\n        ]\n        self.visited = []\n\n    def add_edge(self, u, v, weight):\n        self.edges[u][v] = weight\n\n\ndef dijkstra(graph, start_vertex):\n    D = {v: float(\"inf\") for v in range(graph.v)}\n    D[start_vertex] = 0\n\n    pq = PriorityQueue()\n    pq.put((0, start_vertex))\n\n    while not pq.empty():\n        (dist, current_vertex) = pq.get()\n        graph.visited.append(current_vertex)\n\n        for neighbor in range(graph.v):\n            if graph.edges[current_vertex][neighbor] != -1:\n                distance = graph.edges[current_vertex][neighbor]\n                if neighbor not in graph.visited:\n                    old_cost = D[neighbor]\n                    new_cost = D[current_vertex] + distance\n                    if new_cost < old_cost:\n                        pq.put((new_cost, neighbor))\n                        D[neighbor] = new_cost\n    return D\n\n\ng = Graph(rows * cols)\nfor i in range(rows):\n    for j in range(cols):\n\n        if i < rows - 1:\n            g.add_edge((i + 1) * cols + j, i * cols + j, risks[i][j])\n            g.add_edge(i * cols + j, (i + 1) * cols + j, risks[i + 1][j])\n\n        if j < cols - 1:\n            g.add_edge(i * cols + j + 1, i * cols + j, risks[i][j])\n            g.add_edge(i * cols + j, i * cols + j + 1, risks[i][j + 1])\n\n\nD = dijkstra(g, 0)\nprint(f\"Cost of shortest path is {D[rows*cols-1]}\")\n
with open(\"day15_input.txt\", \"r\") as f:\n    lines = [[int(d) for d in line] for line in f.read().splitlines()]\n\nrows, cols = len(lines), len(lines[0])\n\n\nlines_5x = [[0] * cols * 5 for i in range(rows * 5)]\nfor ii in range(5):\n    for jj in range(5):\n        for i in range(rows):\n            for j in range(cols):\n                lines_5x[ii * rows + i][jj * cols + j] = (\n                    lines[i][j] + ii + jj - 1\n                ) % 9 + 1\n\n\n# Using the networkx library instead\n\nimport networkx as nx\n\ng = nx.DiGraph()\nrows *= 5\ncols *= 5\n\nfor i in range(rows):\n    for j in range(cols):\n        if i < rows - 1:\n            g.add_edge((i, j), (i + 1, j), weight=lines_5x[i + 1][j])\n            g.add_edge((i + 1, j), (i, j), weight=lines_5x[i][j])\n\n        if j < cols - 1:\n            g.add_edge((i, j), (i, j + 1), weight=lines_5x[i][j + 1])\n            g.add_edge((i, j + 1), (i, j), weight=lines_5x[i][j])\n\npaths = nx.shortest_path(\n    g,\n    source=(0, 0),\n    target=(rows - 1, cols - 1),\n    weight=\"weight\",\n)\n\n# print(paths)\n\ncost = 0\nfor i, j in paths[1:]:\n    cost += lines_5x[i][j]\n\nprint(f\"Cost of shortest path is {cost}\")\n
Day 16 Part 1
with open(\"day16_input.txt\", \"r\") as f:\n    hexadecimal = f.read().strip()\n\nprint(f\"Hex: {hexadecimal}\")\n\n\ndef hex2bin(h):\n    return bin(int(h, 16))[2:].zfill(len(h) * 4)\n\n\nb = hex2bin(hexadecimal)\nprint(f\"Bin: {b}\")\n\nprint()\n\n\ndef decode_header(b):\n    packet_version = b[:3]\n    packet_type_id = b[3:6]\n\n    return int(packet_version, 2), int(packet_type_id, 2), b[6:]\n\n\ndef decode_literal(b):\n    value = \"\"\n\n    while b:\n        seg = b[:5]\n        value += seg[-4:]\n        b = b[5:]\n        if seg[0] == \"0\":\n            break\n\n    return value, b\n\n\ndef decode_operator(b):\n    length_type_id = b[:1]\n\n    if length_type_id == \"0\":\n        length_of_subpackets = int(b[1:16], 2)\n\n        remaining = b[16 + length_of_subpackets :]\n        b = b[16 : 16 + length_of_subpackets]\n        number_of_subpackets = -1\n    else:\n        number_of_subpackets = int(b[1:12], 2)\n        b = b[12:]\n        remaining = None\n\n    return length_type_id, number_of_subpackets, b, remaining\n\n\nresult = []\n\n\ndef decode(b):\n    while b:\n        if all(c == \"0\" for c in b):\n            return\n\n        packet_version, packet_type_id, b = decode_header(b)\n        result.append(packet_version)\n        print(f\"packet_version: {packet_version}, packet_type_id: {packet_type_id}\")\n        if packet_type_id == 4:\n            value, b = decode_literal(b)\n            print(f\"Literal value {value} is {int(value, 2)}.\")\n        else:\n            length_type_id, number_of_subpackets, block, remaining = decode_operator(b)\n            print(\n                f\"length_type_id: {length_type_id},\",\n                f\"number_of_subpackets: {number_of_subpackets},\",\n            )\n            if number_of_subpackets == -1:\n                b = remaining\n                decode(block)\n            else:\n                b = block\n                return decode(b)\n\n    return\n\n\ndecode(b)\nprint()\nprint(f\"Result: {result} -> {sum(result)}\")\n
"},{"location":"2022/","title":"Advent of Code 2022","text":"Day 01 Part 1Part 2
max_calories = 0\ncalories = 0\n\nwith open(\"day01_input.txt\") as f:\n    for line in f:\n        if not line.strip():\n            if calories > max_calories:\n                max_calories = calories\n            calories = 0\n            continue\n        calories += int(line)\n\nprint(max_calories)\n
all_calories = []\ncalories = 0\n\nwith open(\"day01_input.txt\") as f:\n    for line in f:\n        if not line.strip():\n            all_calories.append(calories)\n            calories = 0\n            continue\n        calories += int(line)\n\nprint(sum(sorted(all_calories)[-3:]))\n
Day 02 Part 1Part 2
score = 0\n\nop_order = [\"A\", \"B\", \"C\"]\nme_order = [\"X\", \"Y\", \"Z\"]\nwith open(\"day02_input.txt\") as f:\n    for line in f:\n        op, me = line.strip().split()\n        ind_op = op_order.index(op)\n        ind_me = me_order.index(me)\n        if ind_me == ind_op:\n            score += ind_me + 1 + 3\n        elif any(\n            [\n                ind_me == 1 and ind_op == 0,\n                ind_me == 2 and ind_op == 1,\n                ind_me == 0 and ind_op == 2,\n            ]\n        ):\n            score += ind_me + 1 + 6\n        else:\n            score += ind_me + 1 + 0\n\nprint(score)\n
score = 0\n\nop_order = [\"A\", \"B\", \"C\"]\nme_order = [\"X\", \"Y\", \"Z\"]\nwith open(\"day02_input.txt\") as f:\n    for line in f:\n        op, me = line.strip().split()\n        ind_op = op_order.index(op)\n        ind_me = me_order.index(me)\n        if ind_me == 1:\n            score += ind_op + 1 + 3\n        elif ind_me == 2:\n            shape_map = {\n                0: 1 + 1,\n                1: 2 + 1,\n                2: 0 + 1,\n            }\n            score += shape_map[ind_op] + 6\n        else:\n            shape_map = {\n                0: 2 + 1,\n                1: 0 + 1,\n                2: 1 + 1,\n            }\n            score += shape_map[ind_op] + 0\n\nprint(score)\n
Day 03 Part 1Part 2
priorities = 0\n\nwith open(\"day03_input.txt\") as f:\n    for line in f:\n        line = line.strip()\n        if not line:\n            continue\n        first, second = line[: len(line) // 2], line[len(line) // 2 :]\n        overlap = set(first).intersection(set(second)).pop()\n        if overlap.isupper():\n            priorities += ord(overlap) - ord(\"A\") + 27\n        else:\n            priorities += ord(overlap) - ord(\"a\") + 1\n\nprint(priorities)\n
priorities = 0\n\nwith open(\"day03_input.txt\") as f:\n    groups = f.readlines()\n    groups = [groups[3 * i : 3 * i + 3] for i in range(0, len(groups) // 3)]\n\n    for g in groups:\n        items = None\n        for line in g:\n            line = line.strip()\n            if not items:\n                items = set(line)\n            else:\n                items = items.intersection(set(line))\n        overlap = items.pop()\n\n        if overlap.isupper():\n            priorities += ord(overlap) - ord(\"A\") + 27\n        else:\n            priorities += ord(overlap) - ord(\"a\") + 1\n\nprint(priorities)\n
Day 04 Part 1Part 2
count = 0\n\nwith open(\"day04_input.txt\") as f:\n    sections = f.readlines()\n    for section in sections:\n        section = section.strip()\n        r1, r2 = section.split(\",\")\n\n        r1_start, r1_stop = int(r1.split(\"-\")[0]), int(r1.split(\"-\")[1]) + 1\n        r1 = set(range(r1_start, r1_stop))\n\n        r2_start, r2_stop = int(r2.split(\"-\")[0]), int(r2.split(\"-\")[1]) + 1\n        r2 = set(range(r2_start, r2_stop))\n\n        if r1.issuperset(r2) or r2.issuperset(r1):\n            count += 1\n\nprint(count)\n
count = 0\n\nwith open(\"day04_input.txt\") as f:\n    sections = f.readlines()\n    for section in sections:\n        section = section.strip()\n        r1, r2 = section.split(\",\")\n\n        r1_start, r1_stop = int(r1.split(\"-\")[0]), int(r1.split(\"-\")[1]) + 1\n        r1 = set(range(r1_start, r1_stop))\n\n        r2_start, r2_stop = int(r2.split(\"-\")[0]), int(r2.split(\"-\")[1]) + 1\n        r2 = set(range(r2_start, r2_stop))\n\n        if r1.intersection(r2):\n            count += 1\n\nprint(count)\n
Day 06 Part 1Part 2
with open(\"day06_input.txt\") as f:\n    buffer = f.read()\n\n    for i in range(0, len(buffer) - 4):\n        if len(set(buffer[i : i + 4])) == 4:\n            break\n\n    print(i + 4)\n
with open(\"day06_input.txt\") as f:\n    buffer = f.read()\n\n    offset = 14\n    for i in range(0, len(buffer) - offset):\n        if len(set(buffer[i : i + offset])) == offset:\n            break\n\n    print(i + offset)\n
"},{"location":"2023/","title":"Advent of Code 2023","text":"Day 01 Part 1
with open(\"day01_input.txt\", \"r\") as f:\n    data = [\"\".join(c for c in row if c.isdigit()) for row in f.read().splitlines()]\n\nvalues = [int(d[0] + d[-1]) for d in data]\nprint(sum(values))\n
"}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Home","text":""},{"location":"#advent-of-code","title":"Advent of Code","text":"
  • 2023
  • 2022
  • 2021
  • 2019
  • 2018
  • 2015
"},{"location":"2015/","title":"Advent of Code 2015","text":"Day 01 Part 1Part 2
with open(\"day01_input.txt\", \"r\") as f:\n    s = f.read()\n\nfloor = 0\nfor c in s:\n    if c == \"(\":\n        floor += 1\n    elif c == \")\":\n        floor -= 1\n\nprint(floor)\n
with open(\"day01_input.txt\", \"r\") as f:\n    s = f.read()\n\nfloor = 0\nfor i in range(len(s)):\n    c = s[i]\n    if c == \"(\":\n        floor += 1\n    elif c == \")\":\n        floor -= 1\n    if floor == -1:\n        break\n\nprint(i + 1)\n
"},{"location":"2018/","title":"Advent of Code 2018","text":"Day 01 Part 1
with open(\"day01_input.txt\", \"r\") as f:\n    changes = [int(i) for i in f.read().splitlines()]\n\nprint(sum(changes))\n
"},{"location":"2019/","title":"Advent of Code 2019","text":"Day 01 Part 1
with open(\"day01_input.txt\", \"r\") as f:\n    data = [int(i) for i in f.read().splitlines()]\n\nfuels = [mass // 3 - 2 for mass in data]\nprint(sum(fuels))\n
"},{"location":"2021/","title":"Advent of Code 2021","text":"Day 01 Part 1Part 2
with open(\"day01_input.txt\", \"r\") as f:\n    data = [int(i) for i in f.read().splitlines()]\n\ncount = 0\nfor i in range(1, len(data)):\n    if data[i] > data[i - 1]:\n        count += 1\n\nprint(count)\n
with open(\"day01_input.txt\", \"r\") as f:\n    data = [int(i) for i in f.read().splitlines()]\n\nthree_measurement_data = []\nfor i in range(2, len(data)):\n    three_measurement_data.append(sum(data[i - 2 : i + 1]))\n\ncount = 0\nfor i in range(1, len(three_measurement_data)):\n    if three_measurement_data[i] > three_measurement_data[i - 1]:\n        count += 1\n\nprint(count)\n
Day 02 Part 1Part 2
with open(\"day02_input.txt\", \"r\") as f:\n    data = [cmd.split() for cmd in f.read().splitlines()]\n\nhorizontal_position, depth = 0, 0\n\nfor action, value in data:\n    value = int(value)\n    if action == \"forward\":\n        horizontal_position += value\n    elif action == \"up\":\n        depth -= value\n    elif action == \"down\":\n        depth += value\n\nprint(horizontal_position, depth)\n\nprint(horizontal_position * depth)\n
with open(\"day02_input.txt\", \"r\") as f:\n    data = [cmd.split() for cmd in f.read().splitlines()]\n\nhorizontal_position, depth, aim = 0, 0, 0\n\nfor action, value in data:\n    value = int(value)\n    if action == \"forward\":\n        horizontal_position += value\n        depth += aim * value\n    elif action == \"up\":\n        aim -= value\n    elif action == \"down\":\n        aim += value\n\n\nprint(horizontal_position, depth, aim)\n\nprint(horizontal_position * depth)\n
Day 03 Part 1Part 2
with open(\"day03_input.txt\", \"r\") as f:\n    data = f.read().splitlines()\n\ncols = len(data[0])\nrows = len(data)\n\ngamma_rate, epsilon_rate = \"\", \"\"\n\nfor col in range(cols):\n    ones = 0\n    for row in range(rows):\n        if data[row][col] == \"1\":\n            ones += 1\n\n    if ones > rows / 2:\n        gamma_rate += \"1\"\n        epsilon_rate += \"0\"\n    else:\n        gamma_rate += \"0\"\n        epsilon_rate += \"1\"\n\nprint(gamma_rate, epsilon_rate)\n\nprint(int(gamma_rate, 2) * int(epsilon_rate, 2))\n
with open(\"day03_input.txt\", \"r\") as f:\n    data = f.read().splitlines()\n\ncols = len(data[0])\n\noxygen_generator_rating, co2_scrubber_rating = \"\", \"\"\n\nselections = data[:]\nfor col in range(cols):\n    ones = 0\n    for row in selections:\n        if row[col] == \"1\":\n            ones += 1\n\n    if ones >= len(selections) / 2:\n        selections = [row for row in selections if row[col] == \"1\"]\n    else:\n        selections = [row for row in selections if row[col] == \"0\"]\n\n    if len(selections) == 1:\n        oxygen_generator_rating += selections[0]\n        break\n\nselections = data[:]\nfor col in range(cols):\n    ones = 0\n    for row in selections:\n        if row[col] == \"1\":\n            ones += 1\n\n    if ones < len(selections) / 2:\n        selections = [row for row in selections if row[col] == \"1\"]\n    else:\n        selections = [row for row in selections if row[col] == \"0\"]\n\n    if len(selections) == 1:\n        co2_scrubber_rating += selections[0]\n        break\n\n\nprint(oxygen_generator_rating, co2_scrubber_rating)\n\nprint(int(oxygen_generator_rating, 2) * int(co2_scrubber_rating, 2))\n
Day 04 Part 1Part 2
with open(\"day04_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\ndraws = lines[0].split(\",\")\n\n\nlines = [line for line in lines[1:] if line]\nboards = []\nfor i in range(0, len(lines) // 5):\n    boards.append([])\n    for j in range(5):\n        boards[i].append(lines[i * 5 + j].split())\n\n\nmarks = {}\nfor i in range(len(boards)):\n    marks[i] = {}\n    for row in range(5):\n        for col in range(5):\n            marks[i][boards[i][row][col]] = (row, col)\n\n\nwinning_locations = []\nfor row in range(5):\n    winning_locations.append([(row, col) for col in range(5)])\nfor col in range(5):\n    winning_locations.append([(row, col) for row in range(5)])\n\n\ndef wins(locations, winning_locations=winning_locations):\n    for winning_location in winning_locations:\n        if all(loc in locations for loc in winning_location):\n            return winning_location\n\n    return None\n\n\nplays = {}\nfor i in range(len(boards)):\n    plays[i] = []\n\nnum_plays = {}\nfor i in range(len(boards)):\n    count = 0\n    for draw in draws:\n        count += 1\n        if draw in marks[i]:\n            plays[i].append(marks[i][draw])\n\n        if wins(plays[i]):\n            num_plays[i] = count, len(plays[i])\n            break\n\n\nfastest_win = min(num_plays, key=lambda x: num_plays[x][0])\nprint(fastest_win)\n\n\nsum_unmarked = 0\nfor row in range(5):\n    for col in range(5):\n        if (row, col) not in plays[fastest_win]:\n            sum_unmarked += int(boards[fastest_win][row][col])\n\nrow, col = plays[fastest_win][-1]\nnum_call = int(boards[fastest_win][row][col])\n\n\nprint(sum_unmarked, num_call)\nprint(sum_unmarked * num_call)\n
with open(\"day04_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\ndraws = lines[0].split(\",\")\n\n\nlines = [line for line in lines[1:] if line]\nboards = []\nfor i in range(0, len(lines) // 5):\n    boards.append([])\n    for j in range(5):\n        boards[i].append(lines[i * 5 + j].split())\n\n\nmarks = {}\nfor i in range(len(boards)):\n    marks[i] = {}\n    for row in range(5):\n        for col in range(5):\n            marks[i][boards[i][row][col]] = (row, col)\n\n\nwinning_locations = []\nfor row in range(5):\n    winning_locations.append([(row, col) for col in range(5)])\nfor col in range(5):\n    winning_locations.append([(row, col) for row in range(5)])\n\n\ndef wins(locations, winning_locations=winning_locations):\n    for winning_location in winning_locations:\n        if all(loc in locations for loc in winning_location):\n            return winning_location\n\n    return None\n\n\nplays = {}\nfor i in range(len(boards)):\n    plays[i] = []\n\nnum_plays = {}\nfor i in range(len(boards)):\n    count = 0\n    for draw in draws:\n        count += 1\n        if draw in marks[i]:\n            plays[i].append(marks[i][draw])\n\n        if wins(plays[i]):\n            num_plays[i] = count, len(plays[i])\n            break\n\n\nlast_win = max(num_plays, key=lambda x: num_plays[x][0])\nprint(last_win)\n\n\nsum_unmarked = 0\nfor row in range(5):\n    for col in range(5):\n        if (row, col) not in plays[last_win]:\n            sum_unmarked += int(boards[last_win][row][col])\n\nrow, col = plays[last_win][-1]\nnum_call = int(boards[last_win][row][col])\n\n\nprint(sum_unmarked, num_call)\nprint(sum_unmarked * num_call)\n
Day 05 Part 1Part 2
with open(\"day05_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\nlines = [line.split(\" -> \") for line in lines]\nlines = [(tuple(line[0].split(\",\")), tuple(line[1].split(\",\"))) for line in lines]\nprint(len(lines))\n\nlines = [\n    ((int(coord1[0]), int(coord1[1])), (int(coord2[0]), int(coord2[1])))\n    for coord1, coord2 in lines\n    if coord1[0] == coord2[0] or coord1[1] == coord2[1]\n]\nprint(len(lines))\n\nfrom collections import Counter\n\ndiagram = Counter()\nfor coord1, coord2 in lines:\n    if coord1[0] == coord2[0]:\n        for i in range(min(coord1[1], coord2[1]), max(coord1[1], coord2[1]) + 1):\n            diagram[(coord1[0], i)] += 1\n    elif coord1[1] == coord2[1]:\n        for i in range(min(coord1[0], coord2[0]), max(coord1[0], coord2[0]) + 1):\n            diagram[(i, coord1[1])] += 1\n\nprint(len([i for i in diagram.values() if i > 1]))\n
with open(\"day05_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\nlines = [line.split(\" -> \") for line in lines]\nlines = [(tuple(line[0].split(\",\")), tuple(line[1].split(\",\"))) for line in lines]\nprint(len(lines))\n\nlines = [\n    ((int(coord1[0]), int(coord1[1])), (int(coord2[0]), int(coord2[1])))\n    for coord1, coord2 in lines\n]\n\nfrom collections import Counter\n\ndiagram = Counter()\nfor coord1, coord2 in lines:\n    if coord1[0] == coord2[0]:\n        for i in range(min(coord1[1], coord2[1]), max(coord1[1], coord2[1]) + 1):\n            diagram[(coord1[0], i)] += 1\n    elif coord1[1] == coord2[1]:\n        for i in range(min(coord1[0], coord2[0]), max(coord1[0], coord2[0]) + 1):\n            diagram[(i, coord1[1])] += 1\n    else:\n        step_x = -1 if coord1[0] - coord2[0] > 0 else 1\n        step_y = -1 if coord1[1] - coord2[1] > 0 else 1\n        for x, y in zip(\n            range(coord1[0], coord2[0] + (1 if step_x > 0 else -1), step_x),\n            range(coord1[1], coord2[1] + (1 if step_y > 0 else -1), step_y),\n        ):\n            diagram[(x, y)] += 1\n\nprint(len([i for i in diagram.values() if i > 1]))\n
Day 06 Part 1Part 2
with open(\"day06_input.txt\", \"r\") as f:\n    fish = [int(i) for i in f.read().strip().split(\",\")]\n\nprint(f\"Initial state: {fish}\")\n\nfor _ in range(80):\n    new_fish = []\n    for i in range(len(fish)):\n\n        fish[i] -= 1\n\n        if fish[i] < 0:\n            fish[i] = 6\n            new_fish.append(8)\n\n    fish.extend(new_fish)\n\n    print(f\"After {str(_+1):2s} day{'s' if _ else ''}: {fish}\")\n\nprint(len(fish))\n
with open(\"day06_input.txt\", \"r\") as f:\n    fish = [int(i) for i in f.read().strip().split(\",\")]\n\n\nfrom collections import Counter\n\nfish = Counter(fish)\nprint(fish)\n\nfor _ in range(256):\n    for i in range(-1, 9):\n        if i == 8:\n            fish[i] = fish[-1]\n        elif i != 6:\n            fish[i] = fish[i + 1]\n        else:\n            fish[i] = fish[-1] + fish[i + 1]\n\n\nprint(sum([v for k, v in fish.items() if k >= 0]))\n
Day 07 Part 1Part 2
with open(\"day07_input.txt\", \"r\") as f:\n    crabs = [int(i) for i in f.read().strip().split(\",\")]\n\nprint(len(crabs))\n\nfrom collections import Counter\n\ncrabs = Counter(crabs)\n\n\noutcome = {}\n\nfor key in crabs:\n    result = 0\n    for key2 in crabs:\n        result += abs(key2 - key) * crabs[key2]\n    outcome[key] = result\n\nmin_key = min(outcome, key=outcome.get)\nprint(min_key)\nprint(outcome[min_key])\n
with open(\"day07_input.txt\", \"r\") as f:\n    crabs = [int(i) for i in f.read().strip().split(\",\")]\n\nprint(len(crabs))\n\nfrom collections import Counter\n\ncrabs = Counter(crabs)\n\n\noutcome = {}\n\nfor key in range(0, max(crabs.keys()) + 1):\n    result = 0\n    for key2 in crabs:\n        result += sum(range(1, abs(key2 - key) + 1)) * crabs[key2]\n    outcome[key] = result\n\nmin_key = min(outcome, key=outcome.get)\nprint(min_key)\nprint(outcome[min_key])\n
Day 08 Part 1Part 2
with open(\"day08_input.txt\", \"r\") as f:\n    obs = [line.split(\" | \") for line in f.read().splitlines()]\n\ncount = 0\nfor o in obs:\n    output_values = o[1].split()\n    for output_value in output_values:\n        if len(output_value) in [2, 3, 4, 7]:\n            count += 1\n\nprint(count)\n
with open(\"day08_input.txt\", \"r\") as f:\n    obs = [line.split(\" | \") for line in f.read().splitlines()]\n\n\ndef _sorted(digit):\n    return \"\".join(sorted(digit))\n\n\ndef solve(digits):\n    mapping = {}\n    five_segs = []\n    six_segs = []\n\n    cf, bcdf, acf, abcdefg = None, None, None, None\n    for digit in digits:\n        if len(digit) == 2:\n            mapping[_sorted(digit)] = \"1\"\n            cf = digit\n        elif len(digit) == 3:\n            mapping[_sorted(digit)] = \"7\"\n            acf = digit\n        elif len(digit) == 4:\n            mapping[_sorted(digit)] = \"4\"\n            bcdf = digit\n        elif len(digit) == 7:\n            mapping[_sorted(digit)] = \"8\"\n            abcdefg = digit\n        elif len(digit) == 5:\n            five_segs.append(digit)\n        elif len(digit) == 6:\n            six_segs.append(digit)\n\n    bd = set(bcdf) - set(cf)\n    eg = set(abcdefg) - (set(cf) | set(bcdf) | set(acf))\n\n    for digit in six_segs:\n        _digit = set(digit)\n        if _digit >= bd and _digit >= eg:\n            mapping[_sorted(digit)] = \"6\"\n        elif _digit >= bd:\n            mapping[_sorted(digit)] = \"9\"\n        elif _digit >= eg:\n            mapping[_sorted(digit)] = \"0\"\n\n    for digit in five_segs:\n        _digit = set(digit)\n        if _digit >= bd:\n            mapping[_sorted(digit)] = \"5\"\n        elif _digit >= eg:\n            mapping[_sorted(digit)] = \"2\"\n        else:\n            mapping[_sorted(digit)] = \"3\"\n\n    return mapping\n\n\ncount = 0\nfor o in obs:\n    output_values = o[1].split()\n    digits = o[0].split()\n    mapping = solve(digits)\n    value = \"\"\n    for digit in output_values:\n        value += mapping[_sorted(digit)]\n\n    count += int(value)\n\nprint(count)\n
Day 09 Part 1Part 2
with open(\"day09_input.txt\", \"r\") as f:\n    obs = [[int(i) for i in line] for line in f.read().splitlines()]\n\n\nlow_points = []\nfor i in range(0, len(obs)):\n    for j in range(0, len(obs[i])):\n        to_compare = []\n        if i > 0:\n            to_compare.append(obs[i - 1][j])\n        if i < len(obs) - 1:\n            to_compare.append(obs[i + 1][j])\n        if j > 0:\n            to_compare.append(obs[i][j - 1])\n        if j < len(obs[i]) - 1:\n            to_compare.append(obs[i][j + 1])\n\n        if all(obs[i][j] < x for x in to_compare):\n            low_points.append(obs[i][j])\n\n\nprint(sum(low_points) + len(low_points))\n
with open(\"day09_input.txt\", \"r\") as f:\n    obs = [[int(i) for i in line] for line in f.read().splitlines()]\n\n\nlow_points = []\nfor i in range(0, len(obs)):\n    for j in range(0, len(obs[i])):\n        to_compare = []\n        if i > 0:\n            to_compare.append(obs[i - 1][j])\n        if i < len(obs) - 1:\n            to_compare.append(obs[i + 1][j])\n        if j > 0:\n            to_compare.append(obs[i][j - 1])\n        if j < len(obs[i]) - 1:\n            to_compare.append(obs[i][j + 1])\n\n        if all(obs[i][j] < x for x in to_compare):\n            low_points.append((i, j))\n\nbasin_sizes = []\n\n\ndef find_basin(i, j, points):\n    points.append((i, j))\n\n    up = i\n    while True:\n        if up > 0:\n            if obs[up - 1][j] > obs[up][j] and obs[up - 1][j] < 9:\n                find_basin(up - 1, j, points)\n                up -= 1\n            else:\n                break\n        else:\n            break\n\n    down = i\n    while True:\n        if down < len(obs) - 1:\n            if obs[down + 1][j] > obs[down][j] and obs[down + 1][j] < 9:\n                find_basin(down + 1, j, points)\n                down += 1\n            else:\n                break\n        else:\n            break\n\n    left = j\n    while True:\n        if left > 0:\n            if obs[i][left - 1] > obs[i][left] and obs[i][left - 1] < 9:\n                find_basin(i, left - 1, points)\n                left -= 1\n            else:\n                break\n        else:\n            break\n\n    right = j\n    while True:\n        if right < len(obs[i]) - 1:\n            if obs[i][right + 1] > obs[i][right] and obs[i][right + 1] < 9:\n                find_basin(i, right + 1, points)\n                right += 1\n            else:\n                break\n        else:\n            break\n\n\nfor i, j in low_points:\n    points = []\n    find_basin(i, j, points)\n    basin_sizes.append(len(set(points)))\n\nimport functools\n\nprint(functools.reduce(lambda x, y: x * y, sorted(basin_sizes)[-3:]))\n
Day 10 Part 1Part 2
with open(\"day10_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\nmapping = {\n    \")\": 3,\n    \"]\": 57,\n    \"}\": 1197,\n    \">\": 25137,\n}\n\nmatch = {\n    \")\": \"(\",\n    \"]\": \"[\",\n    \"}\": \"{\",\n    \">\": \"<\",\n}\n\n\ndef check(line):\n    stack = []\n    for c in line:\n        if c in match.values():\n            stack.append(c)\n        elif c in match.keys():\n            if len(stack) == 0:\n                return mapping[c]\n            last = stack.pop()\n            if last != match[c]:\n                return mapping[c]\n\n    return 0\n\n\nprint(sum(check(line) for line in lines))\n
with open(\"day10_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\nmapping = {\n    \"(\": 1,\n    \"[\": 2,\n    \"{\": 3,\n    \"<\": 4,\n}\n\nmatch = {\n    \")\": \"(\",\n    \"]\": \"[\",\n    \"}\": \"{\",\n    \">\": \"<\",\n}\n\n\ndef check(line):\n    stack = []\n    for c in line:\n        if c in match.values():\n            stack.append(c)\n        elif c in match.keys():\n            if len(stack) == 0:\n                return 0\n            last = stack.pop()\n            if last != match[c]:\n                return 0\n\n    if len(stack) == 0:\n        return 0\n\n    score = 0\n    while len(stack) > 0:\n        last = stack.pop()\n        score *= 5\n        score += mapping[last]\n\n    return score\n\n\nscores = [check(line) for line in lines]\nscores = [s for s in scores if s > 0]\nprint(len(scores))\nprint(sorted(scores)[len(scores) // 2])\n
Day 11 Part 1Part 2
with open(\"day11_input.txt\", \"r\") as f:\n    obs = [[int(i) for i in line] for line in f.read().splitlines()]\n\n\ndef increase(obs):\n    for i in range(len(obs)):\n        for j in range(len(obs[i])):\n            obs[i][j] += 1\n\n\ndef has_flash(obs):\n    locations = []\n    for i in range(len(obs)):\n        for j in range(len(obs[i])):\n            if obs[i][j] > 9:\n                locations.append((i, j))\n    return locations\n\n\ndef display(obs):\n    for i in range(len(obs)):\n        print(\"\".join([str(i) for i in obs[i]]))\n\n\nfrom collections import Counter\n\nprint(\"Before any steps:\")\ndisplay(obs)\nprint()\n\ncount = 0\nfor s in range(100):\n    increase(obs)\n\n    flashes = set()\n    while True:\n        locations = has_flash(obs)\n        flashes.update(locations)\n\n        if locations:\n            c = Counter()\n            for i, j in locations:\n                obs[i][j] = 0\n                if i > 0:\n                    c[(i - 1, j)] += 1\n                    if j > 0:\n                        c[(i - 1, j - 1)] += 1\n                    if j < len(obs[i]) - 1:\n                        c[(i - 1, j + 1)] += 1\n                if i < len(obs) - 1:\n                    c[(i + 1, j)] += 1\n                    if j > 0:\n                        c[(i + 1, j - 1)] += 1\n                    if j < len(obs[i]) - 1:\n                        c[(i + 1, j + 1)] += 1\n                if j > 0:\n                    c[(i, j - 1)] += 1\n                if j < len(obs[i]) - 1:\n                    c[(i, j + 1)] += 1\n            for i, j in c:\n                if (i, j) not in flashes:\n                    obs[i][j] += c[(i, j)]\n            if c:\n                continue\n        break\n\n    print(f\"After step {s+1}:\")\n    display(obs)\n    print(f\"Flashes: {len(flashes)}\")\n    print()\n\n    count += len(flashes)\n\nprint(f\"Total flashes: {count}\")\n
with open(\"day11_input.txt\", \"r\") as f:\n    obs = [[int(i) for i in line] for line in f.read().splitlines()]\n\n\ndef increase(obs):\n    for i in range(len(obs)):\n        for j in range(len(obs[i])):\n            obs[i][j] += 1\n\n\ndef has_flash(obs):\n    locations = []\n    for i in range(len(obs)):\n        for j in range(len(obs[i])):\n            if obs[i][j] > 9:\n                locations.append((i, j))\n    return locations\n\n\ndef display(obs):\n    for i in range(len(obs)):\n        print(\"\".join([str(i) for i in obs[i]]))\n\n\nfrom collections import Counter\n\n\nprint(\"Before any steps:\")\ndisplay(obs)\nprint()\n\n\ncount = 0\noctopuses = sum([len(obs[i]) for i in range(len(obs))])\nwhile True:\n    increase(obs)\n\n    flashes = set()\n    while True:\n        locations = has_flash(obs)\n        flashes.update(locations)\n\n        if locations:\n            c = Counter()\n            for i, j in locations:\n                obs[i][j] = 0\n                if i > 0:\n                    c[(i - 1, j)] += 1\n                    if j > 0:\n                        c[(i - 1, j - 1)] += 1\n                    if j < len(obs[i]) - 1:\n                        c[(i - 1, j + 1)] += 1\n                if i < len(obs) - 1:\n                    c[(i + 1, j)] += 1\n                    if j > 0:\n                        c[(i + 1, j - 1)] += 1\n                    if j < len(obs[i]) - 1:\n                        c[(i + 1, j + 1)] += 1\n                if j > 0:\n                    c[(i, j - 1)] += 1\n                if j < len(obs[i]) - 1:\n                    c[(i, j + 1)] += 1\n            for i, j in c:\n                if (i, j) not in flashes:\n                    obs[i][j] += c[(i, j)]\n            if c:\n                continue\n        break\n\n    print(f\"After step {count+1}:\")\n    display(obs)\n    print(f\"Flashes: {len(flashes)}\")\n    print()\n\n    count += 1\n    if len(flashes) == octopuses:\n        break\n\nprint(f\"Total steps: {count}\")\n
Day 12 Part 1Part 2
with open(\"day12_input.txt\", \"r\") as f:\n    segs = f.read().splitlines()\n\n\ngraph = {}\nfor seg in segs:\n    node1, node2 = seg.split(\"-\")\n    if node1 not in graph:\n        graph[node1] = [node2]\n    else:\n        graph[node1].append(node2)\n\n    if node2 not in graph:\n        graph[node2] = [node1]\n    else:\n        graph[node2].append(node1)\n\nfrom pprint import pprint\n\npprint(graph)\n\n\npaths = []\n\n\ndef breadth_first_search(graph, start, end, path=[]):\n    path = path + [start]\n    if start == end:\n        paths.append(path)\n    if start not in graph:\n        return None\n    for node in graph[start]:\n        if node not in path or node.isupper():\n            newpath = breadth_first_search(graph, node, end, path)\n            if newpath:\n                paths.append(newpath)\n    return None\n\n\nbreadth_first_search(graph, \"start\", \"end\")\n\nfor path in paths:\n    print(\",\".join(path))\n\nprint(len(paths))\n
with open(\"day12_input.txt\", \"r\") as f:\n    segs = f.read().splitlines()\n\n\ngraph = {}\nfor seg in segs:\n    node1, node2 = seg.split(\"-\")\n    if node1 not in graph:\n        graph[node1] = [node2]\n    else:\n        graph[node1].append(node2)\n\n    if node2 not in graph:\n        graph[node2] = [node1]\n    else:\n        graph[node2].append(node1)\n\nfrom pprint import pprint\n\npprint(graph)\n\n\npaths = []\n\n\ndef remaining(path, node):\n    others = [\n        n for n in path if n != node and n.islower() and n not in [\"start\", \"end\"]\n    ]\n\n    return all(path.count(n) <= 1 for n in others)\n\n\ndef breadth_first_search(graph, start, end, path=[]):\n\n    path = path + [start]\n    if start == end:\n        paths.append(path)\n    if start not in graph:\n        return None\n    for node in graph[start]:\n        if (\n            node not in path\n            or node.isupper()\n            or (\n                node not in [\"start\", \"end\"]\n                and node.islower()\n                and path.count(node) < 2\n                and remaining(path, node)\n            )\n        ):\n            newpath = breadth_first_search(graph, node, end, path)\n            if newpath:\n                paths.append(newpath)\n    return None\n\n\nbreadth_first_search(graph, \"start\", \"end\")\n\nfor path in paths:\n    print(\",\".join(path))\n\nprint(len(paths))\n
Day 13 Part 1Part 2
with open(\"day13_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\ndots = []\nactions = []\nfor line in lines:\n    if not line:\n        continue\n    if \",\" in line:\n        x, y = line.split(\",\")\n        dots.append((int(x), int(y)))\n    else:\n        actions.append(line.split()[-1].split(\"=\"))\n\nprevious = dots[:]\n\nfor axis, value in actions:\n    result = []\n    value = int(value)\n    if axis == \"x\":\n        for dot in previous:\n            if dot[0] < value:\n                result.append((dot[0], dot[1]))\n            else:\n                result.append((2 * value - dot[0], dot[1]))\n\n    elif axis == \"y\":\n        for dot in previous:\n            if dot[1] < value:\n                result.append((dot[0], dot[1]))\n            else:\n                result.append((dot[0], 2 * value - dot[1]))\n\n    print(len(set(result)))\n\n    previous = result[:]\n
with open(\"day13_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\ndots = []\nactions = []\nfor line in lines:\n    if not line:\n        continue\n    if \",\" in line:\n        x, y = line.split(\",\")\n        dots.append((int(x), int(y)))\n    else:\n        actions.append(line.split()[-1].split(\"=\"))\n\nprevious = dots[:]\n\nfor axis, value in actions:\n    result = []\n    value = int(value)\n    if axis == \"x\":\n        for dot in previous:\n            if dot[0] < value:\n                result.append((dot[0], dot[1]))\n            else:\n                result.append((2 * value - dot[0], dot[1]))\n\n    elif axis == \"y\":\n        for dot in previous:\n            if dot[1] < value:\n                result.append((dot[0], dot[1]))\n            else:\n                result.append((dot[0], 2 * value - dot[1]))\n\n    print(len(set(result)))\n\n    previous = result[:]\n\nmax_x = max(result, key=lambda x: x[0])[0]\nmax_y = max(result, key=lambda x: x[1])[1]\nprint(max_x, max_y)\n\nfor y in range(max_y + 1):\n    for x in range(max_x + 1):\n        if (x, y) in result:\n            print(\"#\", end=\"\")\n        else:\n            print(\" \", end=\"\")\n    print()\n\nfrom PIL import Image\n\nimg = Image.new(\"RGB\", (max_x + 1, max_y + 1), \"black\")\npixels = img.load()\nfor dot in set(result):\n    pixels[dot[0], dot[1]] = (255, 255, 255)\nimg.show()\n
Day 14 Part 1Part 2
with open(\"day14_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\ntemplate = None\npairs = []\nfor line in lines:\n    if not line:\n        continue\n    if \" -> \" in line:\n        pairs.append(line.split(\" -> \"))\n    else:\n        template = line\n\nprint(f\"Template: {template}\")\n\nfor i in range(10):\n    segs = [template[j : j + 2] for j in range(0, len(template) - 1)]\n\n    for k in range(len(segs)):\n        for pair in pairs:\n            if segs[k] == pair[0]:\n                segs[k] = pair[0][0] + pair[1] + pair[0][1]\n\n    template = segs[0]\n    for seg in segs[1:]:\n        template += seg[-2:]\n\n    print(f\"After step {i+1}: {template}\")\n\nfrom collections import Counter\n\ncounts = Counter(template).most_common()\n\nprint(counts[0][1] - counts[-1][1])\n
with open(\"day14_input.txt\", \"r\") as f:\n    lines = f.read().splitlines()\n\n\ntemplate = None\npairs = []\nfor line in lines:\n    if not line:\n        continue\n    if \" -> \" in line:\n        pairs.append(line.split(\" -> \"))\n    else:\n        template = line\n\nprint(f\"Template: {template}\")\nsegs = [template[j : j + 2] for j in range(0, len(template) - 1)]\n\nfrom collections import Counter\n\ncounts = Counter(segs)\n\n\nfor i in range(40):\n    result = Counter()\n    for key in counts:\n        for pair in pairs:\n            if key == pair[0]:\n                result[key[0] + pair[1]] += counts[key]\n                result[pair[1] + key[1]] += counts[pair[0]]\n\n    counts = result\n\n\nchars = Counter()\nchars[template[0]] += 1\n\nfor key, value in counts.items():\n    chars[key[1]] += value\n\nchars = chars.most_common()\nprint(chars)\nprint(chars[0][1] - chars[-1][1])\n
Day 15 Part 1Part 2
with open(\"day15_input.txt\", \"r\") as f:\n    risks = [[int(d) for d in line] for line in f.read().splitlines()]\n\nrows, cols = len(risks), len(risks[0])\n\n# reference: https://stackabuse.com/dijkstras-algorithm-in-python/\n\nfrom queue import PriorityQueue\n\n\nclass Graph:\n    def __init__(self, num_of_vertices):\n        self.v = num_of_vertices\n        self.edges = [\n            [-1 for i in range(num_of_vertices)] for j in range(num_of_vertices)\n        ]\n        self.visited = []\n\n    def add_edge(self, u, v, weight):\n        self.edges[u][v] = weight\n\n\ndef dijkstra(graph, start_vertex):\n    D = {v: float(\"inf\") for v in range(graph.v)}\n    D[start_vertex] = 0\n\n    pq = PriorityQueue()\n    pq.put((0, start_vertex))\n\n    while not pq.empty():\n        (dist, current_vertex) = pq.get()\n        graph.visited.append(current_vertex)\n\n        for neighbor in range(graph.v):\n            if graph.edges[current_vertex][neighbor] != -1:\n                distance = graph.edges[current_vertex][neighbor]\n                if neighbor not in graph.visited:\n                    old_cost = D[neighbor]\n                    new_cost = D[current_vertex] + distance\n                    if new_cost < old_cost:\n                        pq.put((new_cost, neighbor))\n                        D[neighbor] = new_cost\n    return D\n\n\ng = Graph(rows * cols)\nfor i in range(rows):\n    for j in range(cols):\n\n        if i < rows - 1:\n            g.add_edge((i + 1) * cols + j, i * cols + j, risks[i][j])\n            g.add_edge(i * cols + j, (i + 1) * cols + j, risks[i + 1][j])\n\n        if j < cols - 1:\n            g.add_edge(i * cols + j + 1, i * cols + j, risks[i][j])\n            g.add_edge(i * cols + j, i * cols + j + 1, risks[i][j + 1])\n\n\nD = dijkstra(g, 0)\nprint(f\"Cost of shortest path is {D[rows*cols-1]}\")\n
with open(\"day15_input.txt\", \"r\") as f:\n    lines = [[int(d) for d in line] for line in f.read().splitlines()]\n\nrows, cols = len(lines), len(lines[0])\n\n\nlines_5x = [[0] * cols * 5 for i in range(rows * 5)]\nfor ii in range(5):\n    for jj in range(5):\n        for i in range(rows):\n            for j in range(cols):\n                lines_5x[ii * rows + i][jj * cols + j] = (\n                    lines[i][j] + ii + jj - 1\n                ) % 9 + 1\n\n\n# Using the networkx library instead\n\nimport networkx as nx\n\ng = nx.DiGraph()\nrows *= 5\ncols *= 5\n\nfor i in range(rows):\n    for j in range(cols):\n        if i < rows - 1:\n            g.add_edge((i, j), (i + 1, j), weight=lines_5x[i + 1][j])\n            g.add_edge((i + 1, j), (i, j), weight=lines_5x[i][j])\n\n        if j < cols - 1:\n            g.add_edge((i, j), (i, j + 1), weight=lines_5x[i][j + 1])\n            g.add_edge((i, j + 1), (i, j), weight=lines_5x[i][j])\n\npaths = nx.shortest_path(\n    g,\n    source=(0, 0),\n    target=(rows - 1, cols - 1),\n    weight=\"weight\",\n)\n\n# print(paths)\n\ncost = 0\nfor i, j in paths[1:]:\n    cost += lines_5x[i][j]\n\nprint(f\"Cost of shortest path is {cost}\")\n
Day 16 Part 1
with open(\"day16_input.txt\", \"r\") as f:\n    hexadecimal = f.read().strip()\n\nprint(f\"Hex: {hexadecimal}\")\n\n\ndef hex2bin(h):\n    return bin(int(h, 16))[2:].zfill(len(h) * 4)\n\n\nb = hex2bin(hexadecimal)\nprint(f\"Bin: {b}\")\n\nprint()\n\n\ndef decode_header(b):\n    packet_version = b[:3]\n    packet_type_id = b[3:6]\n\n    return int(packet_version, 2), int(packet_type_id, 2), b[6:]\n\n\ndef decode_literal(b):\n    value = \"\"\n\n    while b:\n        seg = b[:5]\n        value += seg[-4:]\n        b = b[5:]\n        if seg[0] == \"0\":\n            break\n\n    return value, b\n\n\ndef decode_operator(b):\n    length_type_id = b[:1]\n\n    if length_type_id == \"0\":\n        length_of_subpackets = int(b[1:16], 2)\n\n        remaining = b[16 + length_of_subpackets :]\n        b = b[16 : 16 + length_of_subpackets]\n        number_of_subpackets = -1\n    else:\n        number_of_subpackets = int(b[1:12], 2)\n        b = b[12:]\n        remaining = None\n\n    return length_type_id, number_of_subpackets, b, remaining\n\n\nresult = []\n\n\ndef decode(b):\n    while b:\n        if all(c == \"0\" for c in b):\n            return\n\n        packet_version, packet_type_id, b = decode_header(b)\n        result.append(packet_version)\n        print(f\"packet_version: {packet_version}, packet_type_id: {packet_type_id}\")\n        if packet_type_id == 4:\n            value, b = decode_literal(b)\n            print(f\"Literal value {value} is {int(value, 2)}.\")\n        else:\n            length_type_id, number_of_subpackets, block, remaining = decode_operator(b)\n            print(\n                f\"length_type_id: {length_type_id},\",\n                f\"number_of_subpackets: {number_of_subpackets},\",\n            )\n            if number_of_subpackets == -1:\n                b = remaining\n                decode(block)\n            else:\n                b = block\n                return decode(b)\n\n    return\n\n\ndecode(b)\nprint()\nprint(f\"Result: {result} -> {sum(result)}\")\n
"},{"location":"2022/","title":"Advent of Code 2022","text":"Day 01 Part 1Part 2
max_calories = 0\ncalories = 0\n\nwith open(\"day01_input.txt\") as f:\n    for line in f:\n        if not line.strip():\n            if calories > max_calories:\n                max_calories = calories\n            calories = 0\n            continue\n        calories += int(line)\n\nprint(max_calories)\n
all_calories = []\ncalories = 0\n\nwith open(\"day01_input.txt\") as f:\n    for line in f:\n        if not line.strip():\n            all_calories.append(calories)\n            calories = 0\n            continue\n        calories += int(line)\n\nprint(sum(sorted(all_calories)[-3:]))\n
Day 02 Part 1Part 2
score = 0\n\nop_order = [\"A\", \"B\", \"C\"]\nme_order = [\"X\", \"Y\", \"Z\"]\nwith open(\"day02_input.txt\") as f:\n    for line in f:\n        op, me = line.strip().split()\n        ind_op = op_order.index(op)\n        ind_me = me_order.index(me)\n        if ind_me == ind_op:\n            score += ind_me + 1 + 3\n        elif any(\n            [\n                ind_me == 1 and ind_op == 0,\n                ind_me == 2 and ind_op == 1,\n                ind_me == 0 and ind_op == 2,\n            ]\n        ):\n            score += ind_me + 1 + 6\n        else:\n            score += ind_me + 1 + 0\n\nprint(score)\n
score = 0\n\nop_order = [\"A\", \"B\", \"C\"]\nme_order = [\"X\", \"Y\", \"Z\"]\nwith open(\"day02_input.txt\") as f:\n    for line in f:\n        op, me = line.strip().split()\n        ind_op = op_order.index(op)\n        ind_me = me_order.index(me)\n        if ind_me == 1:\n            score += ind_op + 1 + 3\n        elif ind_me == 2:\n            shape_map = {\n                0: 1 + 1,\n                1: 2 + 1,\n                2: 0 + 1,\n            }\n            score += shape_map[ind_op] + 6\n        else:\n            shape_map = {\n                0: 2 + 1,\n                1: 0 + 1,\n                2: 1 + 1,\n            }\n            score += shape_map[ind_op] + 0\n\nprint(score)\n
Day 03 Part 1Part 2
priorities = 0\n\nwith open(\"day03_input.txt\") as f:\n    for line in f:\n        line = line.strip()\n        if not line:\n            continue\n        first, second = line[: len(line) // 2], line[len(line) // 2 :]\n        overlap = set(first).intersection(set(second)).pop()\n        if overlap.isupper():\n            priorities += ord(overlap) - ord(\"A\") + 27\n        else:\n            priorities += ord(overlap) - ord(\"a\") + 1\n\nprint(priorities)\n
priorities = 0\n\nwith open(\"day03_input.txt\") as f:\n    groups = f.readlines()\n    groups = [groups[3 * i : 3 * i + 3] for i in range(0, len(groups) // 3)]\n\n    for g in groups:\n        items = None\n        for line in g:\n            line = line.strip()\n            if not items:\n                items = set(line)\n            else:\n                items = items.intersection(set(line))\n        overlap = items.pop()\n\n        if overlap.isupper():\n            priorities += ord(overlap) - ord(\"A\") + 27\n        else:\n            priorities += ord(overlap) - ord(\"a\") + 1\n\nprint(priorities)\n
Day 04 Part 1Part 2
count = 0\n\nwith open(\"day04_input.txt\") as f:\n    sections = f.readlines()\n    for section in sections:\n        section = section.strip()\n        r1, r2 = section.split(\",\")\n\n        r1_start, r1_stop = int(r1.split(\"-\")[0]), int(r1.split(\"-\")[1]) + 1\n        r1 = set(range(r1_start, r1_stop))\n\n        r2_start, r2_stop = int(r2.split(\"-\")[0]), int(r2.split(\"-\")[1]) + 1\n        r2 = set(range(r2_start, r2_stop))\n\n        if r1.issuperset(r2) or r2.issuperset(r1):\n            count += 1\n\nprint(count)\n
count = 0\n\nwith open(\"day04_input.txt\") as f:\n    sections = f.readlines()\n    for section in sections:\n        section = section.strip()\n        r1, r2 = section.split(\",\")\n\n        r1_start, r1_stop = int(r1.split(\"-\")[0]), int(r1.split(\"-\")[1]) + 1\n        r1 = set(range(r1_start, r1_stop))\n\n        r2_start, r2_stop = int(r2.split(\"-\")[0]), int(r2.split(\"-\")[1]) + 1\n        r2 = set(range(r2_start, r2_stop))\n\n        if r1.intersection(r2):\n            count += 1\n\nprint(count)\n
Day 06 Part 1Part 2
with open(\"day06_input.txt\") as f:\n    buffer = f.read()\n\n    for i in range(0, len(buffer) - 4):\n        if len(set(buffer[i : i + 4])) == 4:\n            break\n\n    print(i + 4)\n
with open(\"day06_input.txt\") as f:\n    buffer = f.read()\n\n    offset = 14\n    for i in range(0, len(buffer) - offset):\n        if len(set(buffer[i : i + offset])) == offset:\n            break\n\n    print(i + offset)\n
"},{"location":"2023/","title":"Advent of Code 2023","text":"Day 01 Part 1
with open(\"day01_input.txt\", \"r\") as f:\n    data = [\"\".join(c for c in row if c.isdigit()) for row in f.read().splitlines()]\n\nvalues = [int(d[0] + d[-1]) for d in data]\nprint(sum(values))\n
"}]} \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 8f1c20e605d03778b2a15efff416b937da03d66b..b7088f7a9a5add94433fdcccc1294e2ee097e864 100644 GIT binary patch delta 13 Ucmb=gXP58h;8=aDcOrWQ03ZVd;s5{u delta 13 Ucmb=gXP58h;K&Z?n#f)O02|o^82|tP