Skip to content

Instantly share code, notes, and snippets.

@strayge
Created January 4, 2023 11:53
Show Gist options
  • Save strayge/629110a4a4245758bfb32cd6d85ee0cd to your computer and use it in GitHub Desktop.
Save strayge/629110a4a4245758bfb32cd6d85ee0cd to your computer and use it in GitHub Desktop.
advent of code 2022 notes
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [],
"source": [
"session = '......'\n",
"import requests\n",
"\n",
"r = requests.get('https://adventofcode.com/2022/day/25/input', cookies={'session': session})\n",
"input = r.text.strip('\\n').splitlines()"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"input = '''\n",
"Sensor at x=2, y=18: closest beacon is at x=-2, y=15\n",
"Sensor at x=9, y=16: closest beacon is at x=10, y=16\n",
"Sensor at x=13, y=2: closest beacon is at x=15, y=3\n",
"Sensor at x=12, y=14: closest beacon is at x=10, y=16\n",
"Sensor at x=10, y=20: closest beacon is at x=10, y=16\n",
"Sensor at x=14, y=17: closest beacon is at x=10, y=16\n",
"Sensor at x=8, y=7: closest beacon is at x=2, y=10\n",
"Sensor at x=2, y=0: closest beacon is at x=2, y=10\n",
"Sensor at x=0, y=11: closest beacon is at x=2, y=10\n",
"Sensor at x=20, y=14: closest beacon is at x=25, y=17\n",
"Sensor at x=17, y=20: closest beacon is at x=21, y=22\n",
"Sensor at x=16, y=7: closest beacon is at x=15, y=3\n",
"Sensor at x=14, y=3: closest beacon is at x=15, y=3\n",
"Sensor at x=20, y=1: closest beacon is at x=15, y=3\n",
"'''.strip().splitlines()"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1=-0-2\n",
"1747\n",
"1=-0-2\n"
]
}
],
"source": [
"def five_to_ten(s: str):\n",
" \"\"\"Convert 5 base digit to 10 base digit.\"\"\"\n",
" result = 0\n",
" for pos, c in enumerate(s[::-1], start=0):\n",
" if c in '012':\n",
" i = int(c)\n",
" elif c == '-':\n",
" i = -1\n",
" elif c == '=':\n",
" i = -2\n",
" result += i * 5 ** pos\n",
" return result\n",
"\n",
"def ten_to_five(number: int) -> str:\n",
" \"\"\"Convert 10 base digit to 5 base digit.\"\"\"\n",
" result = ''\n",
" mid = 0\n",
" pos = 0\n",
" while True:\n",
" pos += 1\n",
" new_mid = 5 ** pos\n",
" if abs(number - mid) < abs(number - new_mid):\n",
" mid = new_mid\n",
" break\n",
" mid = new_mid\n",
" for pos in range(pos, -1, -1):\n",
" options = {\n",
" '=': number + 2 * 5 ** pos,\n",
" '-': number + 1 * 5 ** pos,\n",
" '0': number,\n",
" '1': number - 1 * 5 ** pos,\n",
" '2': number - 2 * 5 ** pos,\n",
" }\n",
" option = sorted(options.items(), key=lambda x: abs(x[1]))[0]\n",
" result += option[0]\n",
" number = option[1]\n",
" # print(f'{option}')\n",
" return result.lstrip('0')\n",
"\n",
"a = '1=-0-2'\n",
"print(a)\n",
"\n",
"b = five_to_ten(a)\n",
"print(b)\n",
"\n",
"c = ten_to_five(b)\n",
"print(c)"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2==221=-002=0-02-000\n"
]
}
],
"source": [
"sum = 0\n",
"for line in input:\n",
" num = five_to_ten(line)\n",
" sum += num\n",
"print(ten_to_five(sum))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7604303\n"
]
}
],
"source": [
"import re\n",
"\n",
"def dist(x1, y1, x2, y2):\n",
" return abs(x1 - x2) + abs(y1 - y2)\n",
"\n",
"sensors = []\n",
"max_dist = 0\n",
"min_x = None\n",
"max_x = None\n",
"for line in input:\n",
" r = re.findall(r'at x=([\\d-]+), y=([\\d-]+).*at x=([\\d-]+), y=([\\d-]+)', line)\n",
" sx, sy = int(r[0][0]), int(r[0][1])\n",
" bx, by = int(r[0][2]), int(r[0][3])\n",
" d = dist(sx, sy, bx, by)\n",
" max_dist = max(max_dist, d)\n",
" min_x = min(min_x, sx) if min_x is not None else sx\n",
" max_x = max(max_x, sx) if max_x is not None else sx\n",
" sensors.append((sx, sy, d))\n",
"# sensors\n",
"\n",
"min_x = max(min_x, 0)\n",
"max_x = min(max_x, 4000000)\n",
"\n",
"count = 0\n",
"for x in range(min_x - max_dist, max_x + max_dist + 1):\n",
" y = 2000000\n",
" for sx, sy, d in sensors:\n",
" if dist(x, y, sx, sy) > d:\n",
" count += 1\n",
" break\n",
"\n",
"print(count-1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"-527 0 1578 163\n",
"20870\n"
]
}
],
"source": [
"def show(map: list):\n",
" sym = {0: '.', 1: '#', 2: 'O'}\n",
" for line in map:\n",
" for x in line:\n",
" X = sym.get(x, x)\n",
" print(f'{X:2} ', end='')\n",
" print()\n",
" print()\n",
"\n",
"min_x, min_y = 1000, 1000\n",
"max_x, max_y = 0, 0\n",
"for line in input:\n",
" for coord in line.split('->'):\n",
" x, y = map(int, coord.strip().split(','))\n",
" min_x = min(min_x, x, 500)\n",
" min_y = min(min_y, y, 0)\n",
" max_x = max(max_x, x, 500)\n",
" max_y = max(max_y, y, 0)\n",
"max_y += 2\n",
"# min_y -= 1\n",
"max_x += 1000\n",
"min_x -= 1000\n",
"\n",
"print(min_x, min_y, max_x, max_y)\n",
"M = [[0] * (max_x - min_x + 1) for _ in range(max_y - min_y + 1)]\n",
"\n",
"# map\n",
"for line in input:\n",
" prev_x, prev_y = None, None\n",
" for coord in line.split('->'):\n",
" x, y = map(int, coord.strip().split(','))\n",
" if prev_x is not None:\n",
" if prev_x == x:\n",
" for i in range(min(prev_y, y), max(prev_y, y) + 1):\n",
" M[i - min_y][x - min_x] = 1\n",
" else:\n",
" for i in range(min(prev_x, x), max(prev_x, x) + 1):\n",
" M[y - min_y][i-min_x] = 1\n",
" M[y - min_y][x - min_x] = 1\n",
" prev_x, prev_y = x, y\n",
"\n",
"# line\n",
"for x in range(min_x, max_x + 1):\n",
" M[max_y - min_y][x - min_x] = 1\n",
"\n",
"def turn() -> bool:\n",
" x, y = 500, 0\n",
" while True:\n",
" # if M[0 - min_y][500 - min_x] == 2:\n",
" # print('done')\n",
" # return False\n",
" turns = [(0, 1), (-1, 1), (1, 1)]\n",
" for dx, dy in turns:\n",
" new_x, new_y = x + dx, y + dy\n",
" if new_y > max_y:\n",
" print('drop')\n",
" return False\n",
" # print(new_x, new_y)\n",
" m = M[new_y - min_y][new_x - min_x]\n",
" if m != 0:\n",
" continue\n",
" # print(f'{x},{y} -> {new_x},{new_y}')\n",
" M[new_y - min_y][new_x - min_x] = 2\n",
" M[y - min_y][x - min_x] = 0\n",
" x, y = new_x, new_y\n",
" break\n",
" else:\n",
" # print('no moves')\n",
" if (x, y) == (500, 0):\n",
" return False\n",
" return True\n",
"\n",
"# show(M)\n",
"i = 0\n",
"while turn():\n",
" i += 1\n",
" if i > 1000000:\n",
" # show(M)\n",
" print('inf')\n",
" break\n",
"else:\n",
" # show(M)\n",
" print(i+1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"input = '''[1,1,3,1,1]\n",
"[1,1,5,1,1]\n",
"\n",
"[[1],[2,3,4]]\n",
"[[1],4]\n",
"\n",
"[9]\n",
"[[8,7,6]]\n",
"\n",
"[[4,4],4,4]\n",
"[[4,4],4,4,4]\n",
"\n",
"[7,7,7,7]\n",
"[7,7,7]\n",
"\n",
"[]\n",
"[3]\n",
"\n",
"[[[]]]\n",
"[[]]\n",
"\n",
"[1,[2,[3,[4,[5,6,7]]]],8,9]\n",
"[1,[2,[3,[4,[5,6,0]]]],8,9]'''.splitlines()"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"23142"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from functools import cmp_to_key\n",
"import json\n",
"\n",
"pairs = []\n",
"\n",
"for i in range(0, len(input), 3):\n",
" line1 = json.loads(input[i])\n",
" line2 = json.loads(input[i+1])\n",
" pairs.append((line1, line2))\n",
"\n",
"def compare(a ,b):\n",
" # print('compare', a, b)\n",
" if isinstance(a, int) and isinstance(b, int):\n",
" if a < b:\n",
" return 1\n",
" if a > b:\n",
" return -1\n",
" return None\n",
" if isinstance(a, list) and isinstance(b, int):\n",
" b = [b]\n",
" if isinstance(a, int) and isinstance(b, list):\n",
" a = [a]\n",
" if isinstance(a, list) and isinstance(b, list):\n",
" for i in range(max(len(a), len(b))):\n",
" try:\n",
" a_item = a[i]\n",
" except IndexError:\n",
" return 1\n",
" try:\n",
" b_item = b[i]\n",
" except IndexError:\n",
" return -1\n",
" c = compare(a_item, b_item)\n",
" if c is not None:\n",
" return c\n",
" return None\n",
"\n",
"# sum = 0\n",
"# for i in range(len(pairs)):\n",
"# num = i + 1\n",
"# pair = pairs[i]\n",
"# result = compare(*pair)\n",
"# if result is True:\n",
"# sum += num\n",
"# sum\n",
"\n",
"pairs2 = []\n",
"for p in pairs:\n",
" pairs2.append(p[0])\n",
" pairs2.append(p[1])\n",
"\n",
"d1 = [[2]]\n",
"d2 = [[6]]\n",
"pairs2.append(d1)\n",
"pairs2.append(d2)\n",
"\n",
"pairs2 = sorted(pairs2, key=cmp_to_key(compare), reverse=True)\n",
"\n",
"mul = 1\n",
"for i, x in enumerate(pairs2, start=1):\n",
" if x == d1 or x == d2:\n",
" mul *= i\n",
"mul"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"388\n"
]
}
],
"source": [
"def show(map: list):\n",
" for line in map:\n",
" for x in line:\n",
" print(f'{x:3} ', end='')\n",
" print()\n",
" print()\n",
"\n",
"pos = (0, 0)\n",
"end = (0, 0)\n",
"M = []\n",
"for i, line in enumerate(input):\n",
" m = []\n",
" for j, c in enumerate(line):\n",
" if c == 'S':\n",
" pos = (i, j)\n",
" m.append(ord('a') - ord('a') + 1)\n",
" elif c == 'E':\n",
" end = (i, j)\n",
" m.append(ord('z') - ord('a') + 2)\n",
" else:\n",
" m.append(ord(c) - ord('a') + 1)\n",
" M.append(m)\n",
"# show(M)\n",
"\n",
"# T = [[-1] * len(M[0]) for _ in range(len(M))]\n",
"# T[pos[0]][pos[1]] = 0\n",
"\n",
"ones = []\n",
"for i in range(len(M)):\n",
" for j in range(len(M[0])):\n",
" if M[i][j] == 1:\n",
" ones.append((i, j))\n",
"\n",
"def round(T, M, end):\n",
" for i in range(len(M)):\n",
" for j in range(len(M[0])):\n",
" if T[i][j] == -1:\n",
" continue\n",
" from_m = M[i][j]\n",
" from_t = T[i][j]\n",
" for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n",
" if (i + di < 0) or (j + dj < 0):\n",
" continue\n",
" try:\n",
" to_m = M[i + di][j + dj]\n",
" to_t = T[i + di][j + dj]\n",
" except IndexError:\n",
" continue\n",
" # if to_m - from_m > 1:\n",
" if from_m - to_m > 1:\n",
" # follow map\n",
" continue\n",
" if (to_t == -1) or (to_t > from_t + 1):\n",
" T[i + di][j + dj] = from_t + 1\n",
"\n",
"\n",
"T = [[-1] * len(M[0]) for _ in range(len(M))]\n",
"T[end[0]][end[1]] = 0\n",
"\n",
"for _ in range(400):\n",
" round(T, M, end)\n",
"dists = []\n",
"for one in ones:\n",
" d = T[one[0]][one[1]]\n",
" if d != -1:\n",
" dists.append(d)\n",
"if dists:\n",
" print(min(dists))\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[140743, 138248, 125166, 109637, 109613, 31129, 31126, 31117]"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import json\n",
"\n",
"\n",
"def parse(input):\n",
" monkeys = {}\n",
" for line in input:\n",
" if line.startswith('Monkey'):\n",
" monkey: int = int(line.split()[1][:-1])\n",
" monkeys[monkey] = {'inspected': 0}\n",
" elif line.startswith(' Starting items:'):\n",
" monkeys[monkey]['items'] = [int(x) for x in line.split(':')[1].split(',')]\n",
" elif line.startswith(' Operation:'):\n",
" monkeys[monkey]['op'] = line.split('= old ')[1].strip()\n",
" elif line.startswith(' Test:'):\n",
" monkeys[monkey]['test'] = int(line.split()[3].strip())\n",
" elif line.startswith(' If true:'):\n",
" monkeys[monkey]['true'] = int(line.strip().split()[5])\n",
" elif line.startswith(' If false:'):\n",
" monkeys[monkey]['false'] = int(line.strip().split()[5])\n",
" return monkeys\n",
"\n",
"def operation(level, op_str, limit):\n",
" op, var = op_str.split()\n",
" if var == 'old':\n",
" var = level\n",
" else:\n",
" var = int(var)\n",
" if op == '+':\n",
" level = level + var\n",
" level = level % limit\n",
" elif op == '*':\n",
" level = level * var\n",
" level = level % limit\n",
" return level\n",
"\n",
"def round(monkeys):\n",
" limit = 1\n",
" for monkey in monkeys.values():\n",
" limit *= monkey['test']\n",
" \n",
" for i, monkey in monkeys.items():\n",
" for _ in range(len(monkey['items'])):\n",
" level = monkey['items'].pop(0)\n",
" level = operation(level, monkey['op'], limit)\n",
" # level = level // 3\n",
" if level % monkey['test'] == 0:\n",
" to_monkey = monkey['true']\n",
" else:\n",
" to_monkey = monkey['false']\n",
" monkeys[to_monkey]['items'].append(level)\n",
" monkey['inspected'] += 1\n",
" return monkeys\n",
"\n",
"\n",
"monkeys = parse(input)\n",
"for r in range(10000):\n",
" # if r % 100 == 0:\n",
" # print(r)\n",
" monkeys = round(monkeys)\n",
"\n",
"\n",
"sorted([m['inspected'] for m in monkeys.values()], reverse=True)"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"19457438264"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"140743*138248"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# # # . . # # # # . # # # # . # # # # . # . . # . # # # . . # # # # . . # # . . \n",
"# . . # . # . . . . . . . # . # . . . . # . # . . # . . # . # . . . . # . . # . \n",
"# . . # . # # # . . . . # . . # # # . . # # . . . # # # . . # # # . . # . . # . \n",
"# # # . . # . . . . . # . . . # . . . . # . # . . # . . # . # . . . . # # # # . \n",
"# . # . . # . . . . # . . . . # . . . . # . # . . # . . # . # . . . . # . . # . \n",
"# . . # . # . . . . # # # # . # # # # . # . . # . # # # . . # . . . . # . . # . \n"
]
}
],
"source": [
"\n",
"\n",
"cycles = 1\n",
"x = 1\n",
"sum = 0\n",
"\n",
"\n",
"img = []\n",
"line = ''\n",
"pos = 1\n",
"\n",
"def draw(cycle, x):\n",
" global img, line, pos\n",
" # linenum = (cycle - 1) // 40\n",
"\n",
" if pos in (x+2, x, x+1):\n",
" sym = '# '\n",
" else:\n",
" sym = '. '\n",
" line += sym\n",
"\n",
" # print(f'{cycle=} {x=} {pos=} {sym=} {line=}')\n",
"\n",
" pos += 1\n",
" if pos == 41:\n",
" img.append(line)\n",
" line = ''\n",
" pos = 1\n",
"\n",
"for line1 in input:\n",
" draw(cycles, x)\n",
" if line1 == 'noop':\n",
" cycles += 1\n",
" elif line1.startswith('addx'):\n",
" \n",
" cycles += 1\n",
" # if cycles in (20,60,100,140,180,220):\n",
" # print(f'{cycles=}: {x=} {sum=} {cycles*x=}')\n",
" # sum += cycles * x\n",
" draw(cycles, x)\n",
" x += int(line1.split()[1])\n",
" cycles += 1\n",
" \n",
" # if cycles in (20,60,100,140,180,220):\n",
" # print(f'{cycles=}: {x=} {sum=} {cycles*x=}')\n",
" # sum += cycles * x\n",
"\n",
"# print(cycles, sum)\n",
"print('\\n'.join(img))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2427\n"
]
}
],
"source": [
"import math\n",
"\n",
"\n",
"# input = '''R 5\n",
"# U 8\n",
"# L 8\n",
"# D 3\n",
"# R 17\n",
"# D 10\n",
"# L 25\n",
"# U 20'''.splitlines()\n",
"\n",
"def distance(x1, y1, x2, y2):\n",
" \"\"\"Calculate distance between two points.\"\"\"\n",
" return math.sqrt(abs(x1 - x2)**2 + abs(y1 - y2)**2)\n",
"\n",
"def show(H, T):\n",
" return\n",
" min_x = min(0, H[0], T[0]) - 3\n",
" max_x = max(0, H[0], T[0]) + 3\n",
" min_y = min(0, H[1], T[1]) - 3\n",
" max_y = max(0, H[1], T[1]) + 3\n",
" for y in range(max_y, min_y, -1):\n",
" for x in range(min_x, max_x + 1):\n",
" if (x, y) == tuple(H):\n",
" print('H', end=' ')\n",
" elif (x, y) == tuple(T):\n",
" print('T', end=' ')\n",
" elif (x, y) == (0, 0):\n",
" print('s', end=' ')\n",
" else:\n",
" print('.', end=' ')\n",
" print()\n",
" print()\n",
"\n",
"visited = set()\n",
"H = [0, 0]\n",
"T = [0, 0]\n",
"tails = [[0,0] for _ in range(9)]\n",
"visited.add(tuple(T))\n",
"\n",
"show(H, T)\n",
"\n",
"def is_move(H, T):\n",
" min_distance = distance(*H, *T)\n",
" if min_distance < 1.7:\n",
" return None\n",
" min_diff = None\n",
" for diff in ((1,0), (-1,0), (0,1), (0,-1), (1,1), (1,-1), (-1,1), (-1,-1)):\n",
" new_pos = (T[0] + diff[0], T[1] + diff[1])\n",
" dist = distance(*H, *new_pos)\n",
" if dist !=0 and dist < min_distance:\n",
" min_distance = dist\n",
" min_diff = diff\n",
" new_pos = None\n",
" if min_diff is not None:\n",
" new_pos = (T[0] + min_diff[0], T[1] + min_diff[1])\n",
" if new_pos and new_pos != H:\n",
" return new_pos\n",
" # T = new_pos\n",
" return None\n",
"\n",
"for line in input:\n",
" direction, repeat = line[0], int(line[1:])\n",
" # print(line)\n",
" for _ in range(repeat):\n",
" if direction == 'R':\n",
" H[0] += 1\n",
" elif direction == 'L':\n",
" H[0] -= 1\n",
" elif direction == 'U':\n",
" H[1] += 1\n",
" elif direction == 'D':\n",
" H[1] -= 1\n",
" else:\n",
" raise ValueError(f'Unknown direction {direction}')\n",
"\n",
" prev = H\n",
" for i in range(9):\n",
" cur = tails[i]\n",
" if new_pos := is_move(prev, cur):\n",
" tails[i] = new_pos\n",
" else:\n",
" break\n",
" prev = tails[i]\n",
" visited.add(tuple(tails[8]))\n",
" # visited.add(tuple(new_pos))\n",
" # new_pos = is_move(H, T)\n",
" # if new_pos:\n",
" # T = new_pos\n",
" # visited.add(tuple(T))\n",
"\n",
" show(H, T)\n",
"print(len(visited))\n",
"\n",
"# print visited\n",
"# for y in range(20, -20, -1):\n",
"# for x in range(-20, 20 + 1):\n",
"# if (x, y) in visited:\n",
"# print('#', end=' ')\n",
"# else:\n",
"# print('.', end=' ')\n",
"# print()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"315495\n"
]
}
],
"source": [
"# input = '''30373\n",
"# 25512\n",
"# 65332\n",
"# 33549\n",
"# 35390'''.splitlines()\n",
"\n",
"def count(value: int, array: list[int]) -> int:\n",
" s = 0\n",
" for x in array:\n",
" s += 1\n",
" if value <= x:\n",
" return s\n",
" return s\n",
"\n",
"sum = 0\n",
"for y in range(len(input)):\n",
" for x in range(len(input[0])):\n",
" value = int(input[y][x])\n",
" left = input[y][:x]\n",
" right = input[y][x+1:]\n",
" top = [input[i][x] for i in range(0, y)]\n",
" botttom = [input[i][x] for i in range(y+1, len(input))]\n",
"\n",
" left = [int(i) for i in left][::-1]\n",
" right = [int(i) for i in right]\n",
" top = [int(i) for i in top][::-1]\n",
" botttom = [int(i) for i in botttom]\n",
"\n",
" score = count(value, left) * count(value, right) * count(value, top) * count(value, botttom)\n",
" sum = max(sum, score)\n",
"\n",
" # print(f'{left=}, {right=} {top=} {botttom=}')\n",
" # print(input[y][x], end=' ')\n",
" # print(f'{sum:<3d} ({count(value, left)} {count(value, right)} {count(value, top)} {count(value, botttom)})', end=' ')\n",
" # if value > max(left) or value > max(right) or value > max(top) or value > max(botttom):\n",
" # sum += 1\n",
" # print()\n",
"print(sum)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"/ tpnspw njsfs bblss wjv 12785886\n"
]
}
],
"source": [
"input2 = '''$ cd /\n",
"$ ls\n",
"dir a\n",
"14848514 b.txt\n",
"8504156 c.dat\n",
"dir d\n",
"$ cd a\n",
"$ ls\n",
"dir e\n",
"29116 f\n",
"2557 g\n",
"62596 h.lst\n",
"$ cd e\n",
"$ ls\n",
"584 i\n",
"$ cd ..\n",
"$ cd ..\n",
"$ cd d\n",
"$ ls\n",
"4060174 j\n",
"8033020 d.log\n",
"5626152 d.ext\n",
"7214296 k'''.splitlines()\n",
"\n",
"dirs = {}\n",
"pwd = ['/']\n",
"for line in input:\n",
" if line.startswith('$ cd '):\n",
" dir = line[5:]\n",
" if dir == '/':\n",
" pwd = ['/']\n",
" elif dir == '..':\n",
" pwd.pop()\n",
" else:\n",
" pwd.append(dir)\n",
" elif line.startswith('$ ls'):\n",
" continue\n",
" else:\n",
" if line.startswith('dir '):\n",
" dir = line[4:]\n",
" else:\n",
" size, name = line.split(' ', 1)\n",
" dirs[tuple(pwd + [name])] = size\n",
"\n",
"sizes = {}\n",
"for path, size in dirs.items():\n",
" for i in range(1, len(path)):\n",
" dir = path[:i]\n",
" dir_str = ' '.join(dir)\n",
" if dir_str not in sizes:\n",
" sizes[dir_str] = 0\n",
" sizes[dir_str] += int(size)\n",
"\n",
"sum = 0\n",
"# for k, size in sizes.items():\n",
"# if size <= 100000:\n",
"# sum += size\n",
"# print(f'{k:<10s} {size}')\n",
"# print(sum)\n",
"for path, size in sorted(sizes.items(), key=lambda x: x[1], reverse=False):\n",
" if 70000000 - sizes['/'] + size >= 30000000:\n",
" print(f'{path:<10s} {size}')\n",
" break\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['s', 'f', 'N', 'l', 'b', 'v', 'C', 'G', 'N', 'l', 'G', 'V', 'c', 'G', 'q', 'q', 'l', 'l', 'C', 'f', 'l', 'R', 'G', 'N', 'Q', 'V', 'v', 'c', 'S', 'h', 'L', 'g', 'Z', 'w', 'W', 'V', 'H', 'r', 'G', 'n', 't', 'T', 'M', 'b', 'F', 'J', 'q', 'f', 'w', 'Z', 'f', 'g', 'z', 'n', 't', 'z', 'B', 'J', 'P', 'v', 'n', 'C', 'l', 'h', 'c', 'g', 'h', 'd', 's', 'N', 'b', 'M', 'J', 'z', 's', 'T', 'q', 'q', 'b', 'p', 'H', 'V', 'g', 'z', 'Z', 'J', 'q', 'b', 'S', 'j', 's', 'l', 'j', 'Q', 'z', 'M', 'p', 'F', 'R', 'd']\n",
"2425\n"
]
}
],
"source": [
"input2 = '''vJrwpWtwJgWrhcsFMMfFFhFp\n",
"jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL\n",
"PmmdzqPrVvPwwTWBwg\n",
"wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn\n",
"ttgJtRGJQctTZtZT\n",
"CrZsJsPPZsGzwwsLwLmpwMDw'''.splitlines()\n",
"\n",
"both = []\n",
"for i in range(0, len(input), 3):\n",
" line1, line2, line3 = input[i:i+3]\n",
" for c in line1:\n",
" if c in line2 and c in line3:\n",
" both.append(c)\n",
" break\n",
"\n",
"sum = 0\n",
"for c in both:\n",
" if ord(c) >= ord('a') and ord(c) <= ord('z'):\n",
" sum += 1 + ord(c) - ord('a')\n",
" elif ord(c) >= ord('A') and ord(c) <= ord('Z'):\n",
" sum += 27 + ord(c) - ord('A')\n",
"print(both)\n",
"print(sum)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10349\n"
]
}
],
"source": [
"# 2022 2\n",
"input2 = ['A Y','B X','C Z']\n",
"\n",
"# sym_map = {'A': 'R', 'B': 'P', 'C': 'S', 'Y': 'P', 'X': 'R', 'Z': 'S'}\n",
"sym_map = {'A': 'R', 'B': 'P', 'C': 'S', 'Y': 'D', 'X': 'L', 'Z': 'W'}\n",
"\n",
"def score(oppo: str, you_outcome: str):\n",
" shape = {'R': 1, 'P': 2, 'S': 3}\n",
" win = {'R': 'P', 'P': 'S', 'S': 'R'}\n",
" lose = {'R': 'S', 'P': 'R', 'S': 'P'}\n",
" if you_outcome == 'W':\n",
" you = win[oppo]\n",
" sum = 6\n",
" elif you_outcome == 'L':\n",
" you = lose[oppo]\n",
" sum = 0\n",
" else:\n",
" you = oppo\n",
" sum = 3\n",
" sum += shape[you]\n",
" # if (you, oppo) in [('R', 'S'), ('P', 'R'),('S', 'P')]:\n",
" # sum += 6\n",
" # elif you == oppo:\n",
" # sum += 3\n",
" # else:\n",
" # sum += 0\n",
" # print(f'{you} vs {oppo} = {sum}')\n",
" return sum\n",
"\n",
"\n",
"total = 0\n",
"for line in input:\n",
" oppo_shape, you_shape = line.split()\n",
" you, oppo = sym_map[you_shape], sym_map[oppo_shape]\n",
" total += score(oppo, you)\n",
"\n",
"print(total)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[(72240, 9), (69625, 1), (69092, 3)]\n",
"210957\n"
]
}
],
"source": [
"# 2022 1\n",
"input = input.strip().splitlines()\n",
"input.append('')\n",
"data = []\n",
"count = 0\n",
"sum = 0\n",
"for num in input:\n",
" if num == '':\n",
" data.append((sum, count))\n",
" sum = 0\n",
" count = 0\n",
" continue\n",
" sum += int(num)\n",
" count += 1\n",
"sorted_data = sorted(data, key=lambda x: x[0], reverse=True)\n",
"print(sorted_data[0:3])\n",
"print(sorted_data[0][0] + sorted_data[1][0] + sorted_data[2][0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"833\n"
]
}
],
"source": [
"input2 = '''2-4,6-8\n",
"2-3,4-5\n",
"5-7,7-9\n",
"2-8,3-7\n",
"6-6,4-6\n",
"2-6,4-8'''.splitlines()\n",
"\n",
"sum = 0\n",
"for line in input:\n",
" s1,s2 = line.split(',')\n",
" n1, n2 = s1.split('-')\n",
" n3, n4 = s2.split('-')\n",
" n1, n2, n3, n4 = int(n1), int(n2), int(n3), int(n4)\n",
" # if ((n3 <= n1 <= n4) and (n3 <= n2 <= n4)) or ((n1 <= n3 <= n2) and (n1 <= n4 <= n2)):\n",
" if (n3 <= n1 <= n4) or (n3 <= n2 <= n4) or (n1 <= n3 <= n2) or (n1 <= n4 <= n2):\n",
" sum += 1\n",
"print(sum)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'GSLCMFBRP'"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#\n",
"from collections import deque\n",
"\n",
"\n",
"input2 = '''\n",
" [D] \n",
"[N] [C] \n",
"[Z] [M] [P]\n",
" 1 2 3 \n",
" \n",
"move 1 from 2 to 1\n",
"move 3 from 1 to 3\n",
"move 2 from 2 to 1\n",
"move 1 from 1 to 2'''.strip('\\n').splitlines()\n",
"\n",
"length = (len(input[0]) + 1) // 4\n",
"stacks = [deque() for _ in range(length)]\n",
"\n",
"commands = 0\n",
"for l, line in enumerate(input):\n",
" if not line.strip(): \n",
" commands = l + 1\n",
" break\n",
" for i in range(length):\n",
" char = line[i*4+1]\n",
" if char != ' ':\n",
" stacks[i].appendleft(char)\n",
"\n",
"for stack in stacks:\n",
" stack.popleft()\n",
"\n",
"for s in input[commands:]:\n",
" parts = s.split()\n",
" count = int(parts[1])\n",
" from_ = int(parts[3]) - 1\n",
" to = int(parts[5]) -1\n",
" # print(1, stacks, count, from_, to)\n",
" temp = deque()\n",
" for _ in range(count):\n",
" temp.append(stacks[from_].pop())\n",
" for _ in range(count):\n",
" stacks[to].append(temp.pop())\n",
" # print(2, stacks)\n",
"\n",
"''.join([s.pop() for s in stacks])\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"qspgbzmjnlrdhv 3037\n"
]
}
],
"source": [
"# 2022 6\n",
"for i in range(14,len(input[0])):\n",
" s = input[0][i-14:i]\n",
" if len(set(s)) == 14:\n",
" print(s, i)\n",
" break\n",
" # print(s, set)\n",
" # break\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.10.8 64-bit",
"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.8"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment