year
stringclasses 1
value | day
stringclasses 25
values | part
stringclasses 2
values | question
stringclasses 50
values | answer
stringclasses 49
values | solution
stringlengths 143
12.8k
| language
stringclasses 3
values |
---|---|---|---|---|---|---|
2024 | 23 | 1 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? | 1194 | from collections import defaultdict
with open('input.txt') as f:
lines = f.read().splitlines()
connections = defaultdict(set)
pairs = [tuple(line.split("-")) for line in lines]
for pair in pairs:
connections[pair[0]].add(pair[1])
connections[pair[1]].add(pair[0])
trios = set()
for pair in pairs:
intersection = connections[pair[0]].intersection(connections[pair[1]])
for val in intersection:
trios.add(tuple(sorted((pair[0], pair[1], val))))
trios_with_t = [trio for trio in trios if any(v.startswith("t") for v in trio)]
print(len(trios_with_t)) | python |
2024 | 23 | 1 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? | 1194 | import argparse
import re
from collections import defaultdict
from typing import Iterable
class Network:
completed_networks: defaultdict[int, set[tuple[str, ...]]]
nodes: defaultdict[str, set[str]]
def __init__(self, text: str):
cache: defaultdict[str, set[str]] = defaultdict(set)
for m in re.finditer(r'(..)-(..)', text):
a = m.group(1)
b = m.group(2)
cache[a].add(b)
cache[b].add(a)
self.nodes = cache
self.completed_networks = defaultdict(set)
def get_names(self):
return self.nodes.keys()
def get_largest_networks(self):
largest_network_length = max(*self.completed_networks.keys())
return list(self.completed_networks[largest_network_length])
def get_complete_network_with_n_nodes(self, n: int):
return list(self.completed_networks[n])
def build_network_for(self, names: Iterable[str]):
networks = self.completed_networks
for name in names:
name_pool = set(self.nodes[name])
depth = 1
work: set[tuple[str, ...]] = {(name,)}
while work:
next_work = set()
for network in work:
# Don't bother with already explored networks
if network in networks[depth]: continue
networks[depth].add(network)
for next_name in name_pool.difference(network):
if self.nodes[next_name].issuperset(network):
next_work.add(tuple(sorted({*network, next_name})))
depth += 1
work = next_work
def solve(input_path: str, /, **_kwargs):
with open(input_path, "r", encoding='utf-8') as file:
input_text = file.read().strip().replace('\r', '')
network = Network(input_text)
names_with_t = [name for name in network.get_names() if name.startswith('t')]
network.build_network_for(names_with_t)
p1 = len(network.get_complete_network_with_n_nodes(3))
print(f'p1 = {p1}')
largest_networks = network.get_largest_networks()
assert len(largest_networks) == 1, "p2 solution should have a single, unique answer"
p2 = ','.join(largest_networks[0])
print(f'p2 = {p2}')
def main():
parser = argparse.ArgumentParser()
parser.add_argument("input", nargs="?", default="sample.txt")
parser.add_argument("-v", "--verbose", action="store_true")
args = parser.parse_args()
solve(args.input, verbose=args.verbose)
if __name__ == "__main__":
main() | python |
2024 | 23 | 1 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? | 1194 | from collections import defaultdict
with open("./day_23.in") as fin:
lines = fin.read().strip().split("\n")
adj = defaultdict(list)
for line in lines:
a, b = line.split("-")
adj[a].append(b)
adj[b].append(a)
triangles = set()
for a in dict(adj):
for i in adj[a]:
for j in adj[a]:
if j in adj[i]:
triangles.add(tuple(sorted([a, i, j])))
ans = 0
for a, b, c in triangles:
if "t" in [a[0], b[0], c[0]]:
ans += 1
print(ans) | python |
2024 | 23 | 1 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? | 1194 | def readfile():
file_name = "23.txt"
mapping = {}
with open(file_name) as f:
tuples = [tuple(line.strip().split("-")) for line in f.readlines()]
# Add reverse order as well
tuples += [(i[1], i[0]) for i in tuples]
# Map all computers to which they are connected
for key, val in tuples:
if key in mapping:
mapping[key].append(val)
else:
mapping[key] = [val]
return mapping
def make_mapping_part1(mapping, computer, depth, lan_party, lan_parties):
# We have reached 3 computers so make sure that we have closed the loop
if depth == 0:
if lan_party[0] == lan_party[-1] and any(
[i.startswith("t") for i in lan_party]
):
lan_parties.add(tuple(sorted(lan_party[:3])))
return
# Check all computers that are connected to the current one
for val in mapping[computer]:
lan_party.append(val)
make_mapping_part1(mapping, val, depth - 1, lan_party, lan_parties)
del lan_party[-1]
def part1(mapping):
lan_parties = set()
# Find all lan parties with exactly 3 computers
for computer in mapping:
make_mapping_part1(mapping, computer, 3, [computer], lan_parties)
print(len(lan_parties))
if __name__ == "__main__":
test_file = False
mapping = readfile()
print("Answer to part 1:")
part1(mapping) | python |
2024 | 23 | 1 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? | 1194 | #!/usr/bin/env python3
from collections import defaultdict
from itertools import combinations
myfile = open("23.in", "r")
lines = myfile.read().strip().splitlines()
myfile.close()
conns = defaultdict(set)
part_one = 0
for line in lines:
a, b = line.split("-")
conns[a].add(b)
conns[b].add(a)
trios = set()
for comp, others in conns.items():
pairs = combinations(others, 2)
for a, b in pairs:
if b in conns[a]:
trios.add(frozenset([comp, a, b]))
for t in trios:
if any(x.startswith("t") for x in t):
part_one += 1
print("Part One:", part_one) | python |
2024 | 23 | 2 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?
Your puzzle answer was 1194.
--- Part Two ---
There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself.
Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party.
In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set:
ka-co
ta-co
de-co
ta-ka
de-ta
ka-de
The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta.
What is the password to get into the LAN party? | bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr | from collections import defaultdict
def bron_kerbosch(connections, R, P, X):
if len(P) == 0 and len(X) == 0:
yield R
while len(P) > 0:
v = P.pop()
yield from bron_kerbosch(connections, R.union(set([v])), P.intersection(connections[v]), X.intersection(connections[v]))
X = X.union(set([v]))
with open('input.txt') as f:
lines = f.read().splitlines()
connections = defaultdict(set)
pairs = [tuple(line.split("-")) for line in lines]
for pair in pairs:
connections[pair[0]].add(pair[1])
connections[pair[1]].add(pair[0])
cliques = bron_kerbosch(connections, set(), set(connections.keys()), set())
print(",".join(sorted(max(cliques, key=len)))) | python |
2024 | 23 | 2 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?
Your puzzle answer was 1194.
--- Part Two ---
There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself.
Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party.
In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set:
ka-co
ta-co
de-co
ta-ka
de-ta
ka-de
The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta.
What is the password to get into the LAN party? | bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr | f = open("input.23.txt")
graph = {}
for p in f:
[a,b] = p.strip().split("-")
if(a in graph.keys()):
graph[a].append(b)
else:
graph[a] = [b]
if(b in graph.keys()):
graph[b].append(a)
else:
graph[b] = [a]
f.close()
triplets = []
v = [] #visited
def gettriplet(n2,n1):
ret = []
for n3 in graph[n2]:
if n1 in graph[n3]:
ret.append('-'.join(sorted([n1,n2,n3])))
return ret
for n in graph.keys():
if n in v:
continue
v.append(n)
for nbr in graph[n]:
t = gettriplet(nbr,n)
if len(t) > 0:
triplets.extend(t)
ans = 0
triplets = list(set(triplets))
for triplet in triplets:
if triplet.find('t') >= 0:
ans += 1
print(triplet)
print(ans) | python |
2024 | 23 | 2 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?
Your puzzle answer was 1194.
--- Part Two ---
There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself.
Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party.
In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set:
ka-co
ta-co
de-co
ta-ka
de-ta
ka-de
The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta.
What is the password to get into the LAN party? | bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr | from collections import defaultdict
import itertools
def is_clique(connections, nodes):
for i, node1 in enumerate(nodes):
for _, node2 in enumerate(nodes[i+1:]):
if node2 not in connections[node1]:
return False
return True
def max_clique_starting_at(connections, node):
neighbors = connections[node]
for i in range(len(neighbors), 1, -1):
for group in itertools.combinations(neighbors, i):
if is_clique(connections, group):
return set([node, *group])
return set()
with open('input.txt') as f:
lines = f.read().splitlines()
connections = defaultdict(set)
pairs = [tuple(line.split("-")) for line in lines]
for pair in pairs:
connections[pair[0]].add(pair[1])
connections[pair[1]].add(pair[0])
cliques = [max_clique_starting_at(connections, node) for node in connections.keys()]
max_clique = max(cliques, key=len)
print(",".join(sorted(max_clique))) | python |
2024 | 23 | 2 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?
Your puzzle answer was 1194.
--- Part Two ---
There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself.
Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party.
In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set:
ka-co
ta-co
de-co
ta-ka
de-ta
ka-de
The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta.
What is the password to get into the LAN party? | bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr | from collections import defaultdict
from copy import deepcopy
with open("input.txt") as input_file:
input_text = input_file.read().splitlines()
connections = defaultdict(set)
for connection in input_text:
person1, person2 = connection.split("-")
connections[person1].add(person2)
connections[person2].add(person1)
max_clique_size = 0
max_clique = set()
def bron_kerbosch(R, P, X):
global max_clique
global max_clique_size
if (not P) and (not X) and len(R) > max_clique_size:
max_clique = R
max_clique_size = len(R)
for person in deepcopy(P):
bron_kerbosch(R | {person}, P & connections[person], X & connections[person])
P -= {person}
X |= {person}
bron_kerbosch(set(), set(connections.keys()), set())
print(",".join(sorted(max_clique))) | python |
2024 | 23 | 2 | --- Day 23: LAN Party ---
As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input).
The network map provides a list of every connection between two computers. For example:
kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn
Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing.
LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers.
In this example, there are 12 such sets of three inter-connected computers:
aq,cg,yn
aq,vc,wq
co,de,ka
co,de,ta
co,ka,ta
de,ka,ta
kh,qp,ub
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
ub,vc,wq
If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers:
co,de,ta
co,ka,ta
de,ka,ta
qp,td,wh
tb,vc,wq
tc,td,wh
td,wh,yn
Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?
Your puzzle answer was 1194.
--- Part Two ---
There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself.
Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party.
In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set:
ka-co
ta-co
de-co
ta-ka
de-ta
ka-de
The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta.
What is the password to get into the LAN party? | bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr | def parse() -> list[tuple[str]]:
return [(line.strip().split("-")[0], line.strip().split("-")[1]) for line in open("input.txt").readlines()]
def generate_graph(connections) -> dict:
nodes = {}
for connection in connections:
if nodes.get(connection[0]) == None:
nodes[connection[0]] = set()
if nodes.get(connection[1]) == None:
nodes[connection[1]] = set()
nodes[connection[0]].add(connection[1])
nodes[connection[1]].add(connection[0])
return nodes
def part1():
connections = parse()
graph = generate_graph(connections)
# Finds a three length loop with at least one containg t
found = set()
for node, neighbors in graph.items():
for neighbor in neighbors:
for neighbors_neighbor in graph[neighbor]:
if node in graph[neighbors_neighbor]:
if node.startswith("t") or neighbor.startswith("t") or neighbors_neighbor.startswith("t"):
s = sorted([node, neighbor, neighbors_neighbor])
found.add(tuple(s))
print(len(found))
def neighbors_all(node: str, graph: dict, subgraph: set) -> bool:
for n in subgraph:
if node not in graph[n]:
return False
return True
def part2():
connections = parse()
graph = generate_graph(connections)
biggest_subgraph = set()
for node, neighbors in graph.items():
result = set()
result.add(node)
for neighbor in neighbors:
if neighbors_all(neighbor, graph, result):
result.add(neighbor)
if len(result) > len(biggest_subgraph):
biggest_subgraph = result
in_order = sorted([x for x in biggest_subgraph])
print(",".join(in_order))
part2() | python |
2024 | 24 | 1 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? | 52956035802096 | import operator
from pprint import pprint
import re
with open("input24.txt") as i:
input = [x.strip() for x in i.readlines()]
test_data_1 = """x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02""".split("\n")
test_data_2 = """x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj""".split("\n")
# input = test_data_1
# input = test_data_2
wires = {}
i = 0
while input[i]!="":
n, v = input[i].split(": ")
wires[n] = int(v)
i += 1
operator_lookup = { "AND": operator.and_, "OR": operator.or_, "XOR": operator.xor }
gates = {}
for l in input[i+1:]:
l, op, r, o = re.match(r"(.+) (AND|OR|XOR) (.+) -> (.+)", l).groups()
gates[o] = (l, operator_lookup[op], r)
def get_bit(name: str) -> int:
if name in wires.keys():
return wires[name]
l, op, r = gates[name]
res = op(get_bit(l), get_bit(r))
return res
bit_count = max([int(x[1:]) for x in gates.keys() if x.startswith("z")])+1
res = 0
for i in range(bit_count-1,-1, -1):
b = get_bit(f"z{i:02}")
res = (res<<1) | b
print(res)
def swap_gates(a, b):
t = gates[a]
gates[a] = gates[b]
gates[b] = t
def add(a: int, b: int) -> int:
for i in range(bit_count):
wires[f"x{i:02}"] = (a>>i)%2
wires[f"y{i:02}"] = (b>>i)%2
res = 0
try:
for i in range(bit_count-1,-1, -1):
c = get_bit(f"z{i:02}")
res = (res<<1) | c
except RecursionError:
raise "Loop detected"
return res
def find_gate(a, op, b):
for k, v in gates.items():
aa, opp, bb = v
if ((a==aa and b==bb) or (a==bb and b==aa)) and opp==op:
return k
return None
def find_gate2(a, op):
for k, v in gates.items():
if (v[0]==a or v[2]==a) and op==v[1]:
return k
print()
# f[i] = x[i] xor y[i]
# g[i] = x[i] and y[i]
# z[i] = (x[i] xor y[i]) xor r[i-1]
# z[i] = f[i] xor r[i-1]
# r[i] = (x[i] and y[i]) or ((x[i] xor y[i]) and r[i-1])
# r[i] = g[i] or (f[i] and r[i-1])
remainders = [find_gate("x00", operator.and_, "y00")]
f = [find_gate(f"x{i:02}", operator.xor, f"y{i:02}") for i in range(0, bit_count)]
g = [find_gate(f"x{i:02}", operator.and_, f"y{i:02}") for i in range(0, bit_count)]
swaps = []
for i in range(1, bit_count-1):
e = find_gate2(f[i], operator.xor)
if e is not None and e!=f"z{i:02}":
swaps.append((e, f"z{i:02}"))
elif e is None:
print(f"No swap found for bit {i}...")
# e = find_gate2(remainders[i-1], operator.xor)
# print(e)
# print(remainders)
# swaps.append()
# x = find_gate2(f[i], operator.and_)
# rr = find_gate2(g[i], operator.or_)
# print(x, rr)
remainders.append(find_gate2(g[i], operator.or_))
print(",".join(sorted([x for y in swaps for x in y]))) | python |
2024 | 24 | 1 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? | 52956035802096 | with open("input.txt") as input_file:
input_text = input_file.read().splitlines()
states = {}
z_wires = []
XOR = []
OR = []
AND = []
for line in input_text:
if ":" in line:
wire, value = line.split(": ")
states[wire] = bool(int(value))
elif "XOR" in line:
wires, output = line.split(" -> ")
wire1, wire2 = wires.split(" XOR ")
XOR.append((wire1, wire2, output))
if output[0] == "z":
z_wires.append(output)
elif "OR" in line:
wires, output = line.split(" -> ")
wire1, wire2 = wires.split(" OR ")
OR.append((wire1, wire2, output))
if output[0] == "z":
z_wires.append(output)
elif "AND" in line:
wires, output = line.split(" -> ")
wire1, wire2 = wires.split(" AND ")
AND.append((wire1, wire2, output))
if output[0] == "z":
z_wires.append(output)
while not all(z in states for z in z_wires):
for op_list, op in ((XOR, "__xor__"), (OR, "__or__"), (AND, "__and__")):
new_list = []
for wire1, wire2, output in op_list:
if states.get(wire1) is not None and states.get(wire2) is not None:
states[output] = getattr(states[wire1], op)(states[wire2])
else:
new_list.append((wire1, wire2, output))
op_list = new_list
place = 0
total = 0
while f"z{place:02d}" in states:
total += int(states[f"z{place:02d}"]) << place
place += 1
print(total) | python |
2024 | 24 | 1 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? | 52956035802096 | wires = {}
gates = []
with open("day24-data.txt") as f:
initial = True
for line in f.readlines():
if line == "\n":
initial = False
continue
if initial:
wires[line.split()[0].strip(':')] = int(line.split()[1])
else:
gate = line.strip('\n').split()
gates.append([gate[0], gate[1], gate[2], gate[4], False])
for gate in gates:
if gate[0] not in wires:
wires[gate[0]] = -1
if gate[2] not in wires:
wires[gate[2]] = -1
all_done = False
while not all_done:
print('*', end='')
all_done = True
for gate in gates:
if wires[gate[0]] != -1 and wires[gate[2]] != -1 and gate[4] == False:
if gate[1] == "AND":
wires[gate[3]] = 1 if wires[gate[0]] + wires[gate[2]] == 2 else 0
elif gate[1] == "OR":
wires[gate[3]] = 1 if wires[gate[0]] + wires[gate[2]] >= 1 else 0
else:
wires[gate[3]] = 1 if wires[gate[0]] != wires[gate[2]] else 0
gate[4] = True
print('.', end='')
elif gate[4] == False:
all_done = False
print()
#print(sorted(wires.items()))
#print(gates)
output = {}
for key, val in wires.items():
if key[0] == 'z':
output[key] = val
sorted_output = dict(sorted(output.items()))
power = 0
dec = 0
for key, val in sorted_output.items():
print(key, val)
dec += val * (2**power)
power += 1
print(dec) | python |
2024 | 24 | 1 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? | 52956035802096 | #!/usr/bin/python3
class Wire:
def __init__(self, name, wire_val):
self.name = name
self.wire_val = wire_val
class Gate:
def __init__(self, logic:str, input_1:str, input_2:str):
self.logic = logic
self.input_1 = input_1
self.input_2 = input_2
def get_output(self, wire_dict:dict) -> str:
if self.logic == "AND":
return ("1" if wire_dict[self.input_1].wire_val == "1"
and wire_dict[self.input_2].wire_val == "1"
else "0")
elif self.logic == "OR":
return ("1" if wire_dict[self.input_1].wire_val == "1"
or wire_dict[self.input_2].wire_val == "1"
else "0")
elif self.logic == "XOR":
return ("1" if wire_dict[self.input_1].wire_val
!= wire_dict[self.input_2].wire_val
else "0")
with open("input.txt") as file:
wires = {}
gates = {}
for line in file:
line = line.strip()
if ":" in line:
wires[line.split(": ")[0]] = Wire(line.split(": ")[0],
line.split(": ")[1])
elif "->" in line:
gates[line.split()[4]] = Gate(line.split()[1],
line.split()[0], line.split()[2])
while any(gate not in wires for gate in gates):
for gate in gates:
if (gates[gate].input_1 in wires.keys()
and gates[gate].input_2 in wires.keys()):
out_val = gates[gate].get_output(wires)
wires[gate] = Wire(gate, out_val)
z_wires = sorted([wires[wire].name for wire in wires
if wires[wire].name.startswith("z")])
z_bits = "".join([wires[z].wire_val for z in z_wires[::-1]])
print('Decimal number output on the wires starting with "z":', int(z_bits, 2)) | python |
2024 | 24 | 1 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? | 52956035802096 | #!/usr/bin/env python3
from collections import deque
myfile = open("24.in", "r")
lines = myfile.read().strip().split("\n\n")
myfile.close()
in_vals, out_vals = lines[0].splitlines(), lines[1].splitlines()
wires = {}
for line in in_vals:
wire, val = line.split(": ")
wires[wire] = int(val)
q = deque(out_vals)
while q:
curr = q.popleft()
wires_in, out_wire = curr.split(" -> ")
left, op, right = wires_in.split(" ")
if left not in wires or right not in wires:
q.append(curr)
continue
result = -1
if op == "XOR":
result = wires[left] ^ wires[right]
elif op == "OR":
result = wires[left] | wires[right]
elif op == "AND":
result = wires[left] & wires[right]
wires[out_wire] = result
x_wires, y_wires, z_wires = [], [], []
for wire in wires.keys():
if "x" in wire:
x_wires.append(wire)
elif "y" in wire:
y_wires.append(wire)
elif "z" in wire:
z_wires.append(wire)
x_wires.sort(reverse=True)
y_wires.sort(reverse=True)
z_wires.sort(reverse=True)
x_digits = [str(wires[w]) for w in x_wires]
y_digits = [str(wires[w]) for w in y_wires]
z_digits = [str(wires[w]) for w in z_wires]
x_dec = int("".join(x_digits), 2)
y_dec = int("".join(y_digits), 2)
z_dec = int("".join(z_digits), 2)
part_one = z_dec
print("Part One:", part_one)
# part two analysis for manual solving
print()
print("Part Two Analysis")
width = len(z_digits)
expected = f"{x_dec + y_dec:0{width}b}"[::-1]
actual = f"{z_dec:0{width}b}"[::-1]
# z wires that must swap
must_swap = []
for line in out_vals:
wires_in, out_wire = line.split(" -> ")
left, op, right = wires_in.split(" ")
if out_wire.startswith("z"):
if out_wire != f"z{width - 1}" and op != "XOR":
must_swap.append(out_wire)
elif out_wire == f"z{width - 1}" and op != "OR":
must_swap.append(out_wire)
print("Must swap:")
print(", ".join(must_swap))
# z wires where something is wrong
wrong_z = []
for i, digit in enumerate(expected):
if digit != actual[i]:
wrong_z.append(f"z{i:02}")
print("Investigate:")
print(", ".join(wrong_z)) | python |
2024 | 24 | 2 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?
Your puzzle answer was 52956035802096.
--- Part Two ---
After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers.
Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.)
The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z.
For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary):
x00: 1
x01: 1
x02: 0
x03: 1
y00: 1
y01: 0
y02: 1
y03: 1
If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000:
z00: 0
z01: 0
z02: 0
z03: 1
z04: 1
Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires.
Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.)
For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05:
x00: 0
x01: 1
x02: 0
x03: 1
x04: 0
x05: 1
y00: 0
y01: 0
y02: 1
y03: 1
y04: 0
y05: 1
x00 AND y00 -> z05
x01 AND y01 -> z02
x02 AND y02 -> z01
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z00
However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y:
x00 AND y00 -> z00
x01 AND y01 -> z01
x02 AND y02 -> z02
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z05
In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05.
Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99.
Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas? | hnv,hth,kfm,tqr,vmv,z07,z20,z28 | class Gate:
def __init__(self, inputs, op, label):
self.inputs = inputs
self.op = op
self.label = label
def __eq__(self, other):
if type(self) == type(other):
return self.op == other.op and self.inputs == other.inputs and self.label == self.label
else:
return False
def __hash__(self):
return hash((self.op, self.inputs, self.label))
def __str__(self):
first, second = sorted(map(str, self.inputs))
return f"({first} {self.op} {second})"
class Circuit:
def __init__(self, input_lines):
self.input_digit_xors = []
self.input_digit_ands = []
self.output_to_expr = {}
self.expr_to_output = {}
self.invalid_input_ands = {}
self.result_gates = []
self.carry_gates = []
self.__parse_input(input_lines)
def __parse_input(self, input_lines):
for line in input_lines:
if "->" in line:
expr, wire = line.split(" -> ")
left, op, right = expr.split(" ")
left, right = sorted((left, right))
self.output_to_expr[wire] = (left, right, op)
self.expr_to_output[(left, right, op)] = wire
input_exprs = dict({(k, v) for (k, v) in self.expr_to_output.items() if k[0].startswith("x")})
for input_expr in sorted(input_exprs.items()):
idx = int(input_expr[0][0][1:])
op = input_expr[0][2]
res = input_expr[1]
if op == 'AND':
self.input_digit_ands.append(res)
if (res.startswith("z")):
self.invalid_input_ands[idx] = res
elif op == 'XOR':
self.input_digit_xors.append(res)
for i in range(len(self.input_digit_xors) + 1):
input_bits_xor_gate = Gate((f"x{i:02}", f"y{i:02}"), "XOR", None)
input_bits_and_gate = Gate((f"x{i:02}", f"y{i:02}"), "AND", None)
if i == 0:
result_gate = input_bits_xor_gate
carry_gate = input_bits_and_gate
else:
result_gate = Gate((input_bits_xor_gate, self.carry_gates[i - 1]), "XOR", None)
carry_gate = Gate((input_bits_and_gate, Gate((input_bits_xor_gate, self.carry_gates[i - 1]), "AND", None)), "OR", None)
self.result_gates.append(result_gate)
self.carry_gates.append(carry_gate)
print(self.result_gates[-1])
with open('input.txt') as f:
lines = f.read().splitlines()
circuit = Circuit(lines)
output_to_expr = dict()
expr_to_output = dict()
for line in lines:
if "->" in line:
expr, wire = line.split(" -> ")
left, op, right = expr.split(" ")
left, right = sorted((left, right))
output_to_expr[wire] = (left, right, op)
expr_to_output[(left, right, op)] = wire
input_exprs = dict({(k, v) for (k, v) in expr_to_output.items() if k[0].startswith("x")})
input_digit_xors = []
input_digit_ands = []
output_digit_carries = []
output_digit_results = []
invalid_input_ands = {}
for input_expr in sorted(input_exprs.items()):
idx = int(input_expr[0][0][1:])
op = input_expr[0][2]
res = input_expr[1]
if op == 'AND':
input_digit_ands.append(res)
if (res.startswith("z")):
print(f"{res} is an AND!")
invalid_input_ands[idx] = res
elif op == 'XOR':
input_digit_xors.append(res)
print(input_digit_xors)
print(input_digit_ands)
swaps = {}
for i in range(len(input_digit_xors)):
if i == 0:
output_digit_results.append(input_digit_xors[0])
output_digit_carries.append(input_digit_ands[0])
else:
result_op = (*sorted((input_digit_xors[i], output_digit_carries[i - 1])), "XOR")
if result_op not in expr_to_output:
incorrect = output_to_expr[f"z{i:02}"]
swap1 = set(result_op).difference(set(incorrect)).pop()
swap2 = set(incorrect).difference(set(result_op)).pop()
print(f"need to swap {swap1} and {swap2}")
swaps[swap1] = swap2
swaps[swap2] = swap1
result_output = expr_to_output[incorrect]
if input_digit_xors[i] == swap1:
print("swapping input digit xors to", swap2)
input_digit_xors[i] = swap2
if input_digit_ands[i] == swap2:
print("swapping input digit ands to", swap1)
input_digit_ands[i] = swap1
else:
result_output = expr_to_output[result_op]
if not result_output.startswith("z"):
expected_output = f"z{i:02}"
if i in invalid_input_ands and expected_output == invalid_input_ands[i]:
print(f"need to swap {expected_output} and {result_output}")
swaps[result_output] = expected_output
swaps[expected_output] = result_output
print("swapping input digit ands to", result_output)
input_digit_ands[i] = result_output
print("swapping result")
result_output = expected_output
else:
print(f"need to swap {expected_output} and {result_output}")
swaps[result_output] = expected_output
swaps[expected_output] = result_output
print("swapping result")
result_output = expected_output
elif int(result_output[1:]) != i:
if result_output in swaps:
expr_to_output[result_op] = swaps[result_output]
else:
expected_output = f"z{i:02}"
print(f"need to swap {result_output} and {expected_output}")
swaps[expected_output] = result_output
swaps[result_output] = expected_output
expr_to_output[result_op] = expected_output
output_digit_results.append(result_output)
rhs_op = (*sorted((input_digit_xors[i], output_digit_carries[i - 1])), "AND")
rhs_output = expr_to_output[rhs_op]
if rhs_output in swaps:
print("swapping rhs")
rhs_output = swaps[rhs_output]
carry_op = (*sorted((input_digit_ands[i], rhs_output)), "OR")
carry_output = expr_to_output[carry_op]
if carry_output in swaps:
print("swapping carry")
carry_output = swaps[carry_output]
output_digit_carries.append(carry_output)
print(f"{i:02} is in {result_output} with carry {carry_output}")
print(",".join(sorted(swaps.keys()))) | python |
2024 | 24 | 2 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?
Your puzzle answer was 52956035802096.
--- Part Two ---
After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers.
Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.)
The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z.
For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary):
x00: 1
x01: 1
x02: 0
x03: 1
y00: 1
y01: 0
y02: 1
y03: 1
If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000:
z00: 0
z01: 0
z02: 0
z03: 1
z04: 1
Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires.
Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.)
For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05:
x00: 0
x01: 1
x02: 0
x03: 1
x04: 0
x05: 1
y00: 0
y01: 0
y02: 1
y03: 1
y04: 0
y05: 1
x00 AND y00 -> z05
x01 AND y01 -> z02
x02 AND y02 -> z01
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z00
However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y:
x00 AND y00 -> z00
x01 AND y01 -> z01
x02 AND y02 -> z02
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z05
In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05.
Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99.
Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas? | hnv,hth,kfm,tqr,vmv,z07,z20,z28 | with open('input.txt') as f:
lines = f.read().splitlines()
output_to_expr = dict()
expr_to_output = dict()
for line in lines:
if "->" in line:
expr, wire = line.split(" -> ")
left, op, right = expr.split(" ")
left, right = sorted((left, right))
output_to_expr[wire] = (left, right, op)
expr_to_output[(left, right, op)] = wire
input_exprs = dict({(k, v) for (k, v) in expr_to_output.items() if k[0].startswith("x")})
input_digit_xors = []
input_digit_ands = []
output_digit_carries = []
output_digit_results = []
invalid_input_ands = {}
for input_expr in sorted(input_exprs.items()):
idx = int(input_expr[0][0][1:])
op = input_expr[0][2]
res = input_expr[1]
if op == 'AND':
input_digit_ands.append(res)
if (res.startswith("z")):
print(f"{res} is an AND!")
invalid_input_ands[idx] = res
elif op == 'XOR':
input_digit_xors.append(res)
print(input_digit_xors)
print(input_digit_ands)
swaps = {}
for i in range(len(input_digit_xors)):
if i == 0:
output_digit_results.append(input_digit_xors[0])
output_digit_carries.append(input_digit_ands[0])
else:
result_op = (*sorted((input_digit_xors[i], output_digit_carries[i - 1])), "XOR")
if result_op not in expr_to_output:
incorrect = output_to_expr[f"z{i:02}"]
swap1 = set(result_op).difference(set(incorrect)).pop()
swap2 = set(incorrect).difference(set(result_op)).pop()
print(f"need to swap {swap1} and {swap2}")
swaps[swap1] = swap2
swaps[swap2] = swap1
result_output = expr_to_output[incorrect]
if input_digit_xors[i] == swap1:
print("swapping input digit xors to", swap2)
input_digit_xors[i] = swap2
if input_digit_ands[i] == swap2:
print("swapping input digit ands to", swap1)
input_digit_ands[i] = swap1
else:
result_output = expr_to_output[result_op]
if not result_output.startswith("z"):
expected_output = f"z{i:02}"
if i in invalid_input_ands and expected_output == invalid_input_ands[i]:
print(f"need to swap {expected_output} and {result_output}")
swaps[result_output] = expected_output
swaps[expected_output] = result_output
print("swapping input digit ands to", result_output)
input_digit_ands[i] = result_output
print("swapping result")
result_output = expected_output
else:
print(f"need to swap {expected_output} and {result_output}")
swaps[result_output] = expected_output
swaps[expected_output] = result_output
print("swapping result")
result_output = expected_output
elif int(result_output[1:]) != i:
if result_output in swaps:
expr_to_output[result_op] = swaps[result_output]
else:
expected_output = f"z{i:02}"
print(f"need to swap {result_output} and {expected_output}")
swaps[expected_output] = result_output
swaps[result_output] = expected_output
expr_to_output[result_op] = expected_output
output_digit_results.append(result_output)
rhs_op = (*sorted((input_digit_xors[i], output_digit_carries[i - 1])), "AND")
rhs_output = expr_to_output[rhs_op]
if rhs_output in swaps:
print("swapping rhs")
rhs_output = swaps[rhs_output]
carry_op = (*sorted((input_digit_ands[i], rhs_output)), "OR")
carry_output = expr_to_output[carry_op]
if carry_output in swaps:
print("swapping carry")
carry_output = swaps[carry_output]
output_digit_carries.append(carry_output)
print(f"{i:02} is in {result_output} with carry {carry_output}")
print(",".join(sorted(swaps.keys()))) | python |
2024 | 24 | 2 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?
Your puzzle answer was 52956035802096.
--- Part Two ---
After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers.
Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.)
The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z.
For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary):
x00: 1
x01: 1
x02: 0
x03: 1
y00: 1
y01: 0
y02: 1
y03: 1
If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000:
z00: 0
z01: 0
z02: 0
z03: 1
z04: 1
Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires.
Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.)
For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05:
x00: 0
x01: 1
x02: 0
x03: 1
x04: 0
x05: 1
y00: 0
y01: 0
y02: 1
y03: 1
y04: 0
y05: 1
x00 AND y00 -> z05
x01 AND y01 -> z02
x02 AND y02 -> z01
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z00
However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y:
x00 AND y00 -> z00
x01 AND y01 -> z01
x02 AND y02 -> z02
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z05
In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05.
Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99.
Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas? | hnv,hth,kfm,tqr,vmv,z07,z20,z28 | from typing import List, Dict
from collections import defaultdict
from part1 import parse_input
def collect_outputs(wire_values: Dict[str, int], prefix: str) -> List[int]:
"""
Collects and returns a list of output values from a dictionary of wire values
where the keys start with a given prefix.
Args:
wire_values (Dict[str, int]): A dictionary containing wire names as keys and their corresponding values.
prefix (str): The prefix to filter the wire names.
Returns:
List[int]: A list of values from the dictionary where the keys start with the specified prefix.
"""
return [value for key, value in sorted(wire_values.items()) if key.startswith(prefix)]
def is_input(operand: str) -> bool:
"""
Checks if the given operand is an input variable.
Args:
operand (str): The operand to check.
Returns:
bool: True if the operand is an input variable ('x' or 'y'), False otherwise.
"""
return operand[0] in 'xy'
def get_usage_map(gates: List[str]) -> Dict[str, List[str]]:
"""
Generates a usage map from a list of gate strings.
Each gate string is expected to be in the format "source -> destination".
The function splits each gate string and maps both the source and destination
to the original gate string in the resulting dictionary.
Args:
gates (List[str]): A list of gate strings.
Returns:
Dict[str, List[str]]: A dictionary where each key is a gate (either source or destination)
and the value is a list of gate strings that include the key.
"""
usage_map = defaultdict(list)
for gate in gates:
parts = gate.split(' ')
usage_map[parts[0]].append(gate)
usage_map[parts[2]].append(gate)
return usage_map
def check_xor_conditions(left: str, right: str, result: str, usage_map: Dict[str, List[str]]) -> bool:
"""
Checks if the given conditions for XOR operations are met.
Args:
left (str): The left operand of the XOR operation.
right (str): The right operand of the XOR operation.
result (str): The result of the XOR operation.
usage_map (Dict[str, List[str]]): A dictionary mapping results to a list of operations that use them.
Returns:
bool: True if the conditions are met, False otherwise.
"""
if is_input(left):
if not is_input(right) or (result[0] == 'z' and result != 'z00'):
return True
usage_ops = [op.split(' ')[1] for op in usage_map[result]]
if result != 'z00' and sorted(usage_ops) != ['AND', 'XOR']:
return True
elif result[0] != 'z':
return True
return False
def check_and_conditions(left: str, right: str, result: str, usage_map: Dict[str, List[str]]) -> bool:
"""
Checks specific conditions based on the provided inputs and usage map.
Args:
left (str): The left operand.
right (str): The right operand.
result (str): The result operand.
usage_map (Dict[str, List[str]]): A dictionary mapping result operands to a list of operations.
Returns:
bool: True if the conditions are met, False otherwise.
Conditions:
1. If 'left' is an input and 'right' is not an input, return True.
2. If the operations associated with 'result' in the usage_map are not all 'OR', return True.
"""
if is_input(left) and not is_input(right):
return True
if [op.split(' ')[1] for op in usage_map[result]] != ['OR']:
return True
return False
def check_or_conditions(left: str, right: str, result: str, usage_map: Dict[str, List[str]]) -> bool:
"""
Checks if the given conditions involving 'left', 'right', and 'result' meet certain criteria.
Args:
left (str): The left operand.
right (str): The right operand.
result (str): The result operand.
usage_map (Dict[str, List[str]]): A dictionary mapping result operands to a list of operations.
Returns:
bool: True if any of the conditions are met:
- Either 'left' or 'right' is an input.
- The operations associated with 'result' in 'usage_map' are not exactly 'AND' and 'XOR'.
Otherwise, returns False.
"""
if is_input(left) or is_input(right):
return True
usage_ops = [op.split(' ')[1] for op in usage_map[result]]
if sorted(usage_ops) != ['AND', 'XOR']:
return True
return False
def find_swapped_wires(wire_values: Dict[str, int], gates: List[str]) -> List[str]:
"""
Identifies and returns a list of swapped wires based on the provided wire values and gate operations.
Args:
wire_values (Dict[str, int]): A dictionary mapping wire names to their integer values.
gates (List[str]): A list of strings representing gate operations in the format "left op right -> result".
Returns:
List[str]: A sorted list of wire names that are identified as swapped.
The function processes each gate operation, checks the operation type (XOR, AND, OR), and applies specific conditions
to determine if the result wire is swapped. It skips gates where the result is 'z45' or the left operand is 'x00'.
"""
usage_map = get_usage_map(gates)
swapped_wires = set()
for gate in gates:
left, op, right, _, result = gate.split(' ')
if result == 'z45' or left == 'x00':
continue
if op == 'XOR' and check_xor_conditions(left, right, result, usage_map):
swapped_wires.add(result)
elif op == 'AND' and check_and_conditions(left, right, result, usage_map):
swapped_wires.add(result)
elif op == 'OR' and check_or_conditions(left, right, result, usage_map):
swapped_wires.add(result)
else:
print(gate, 'unknown op')
return sorted(swapped_wires)
if __name__ == "__main__":
wire_values, gates = parse_input('input.txt')
swapped_wires = find_swapped_wires(wire_values, gates)
result = ','.join(swapped_wires)
print(result) | python |
2024 | 24 | 2 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?
Your puzzle answer was 52956035802096.
--- Part Two ---
After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers.
Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.)
The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z.
For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary):
x00: 1
x01: 1
x02: 0
x03: 1
y00: 1
y01: 0
y02: 1
y03: 1
If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000:
z00: 0
z01: 0
z02: 0
z03: 1
z04: 1
Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires.
Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.)
For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05:
x00: 0
x01: 1
x02: 0
x03: 1
x04: 0
x05: 1
y00: 0
y01: 0
y02: 1
y03: 1
y04: 0
y05: 1
x00 AND y00 -> z05
x01 AND y01 -> z02
x02 AND y02 -> z01
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z00
However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y:
x00 AND y00 -> z00
x01 AND y01 -> z01
x02 AND y02 -> z02
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z05
In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05.
Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99.
Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas? | hnv,hth,kfm,tqr,vmv,z07,z20,z28 | def get_expr_for_output(output):
return output_to_expr[swaps.get(output, output)]
def get_output_for_expr(expr):
output = expr_to_output[expr]
return swaps.get(output, output)
def swap(out_a, out_b):
print(f"SWAP: {out_a} for {out_b}")
swaps[out_a] = out_b
swaps[out_b] = out_a
def find_matching_expr(output, op):
matching = [expr for expr in expr_to_output if expr[2] == op and output in (expr[0], expr[1])]
if len(matching) == 0:
return None
assert len(matching) == 1
return matching[0]
with open('input.txt') as f:
lines = f.read().splitlines()
output_to_expr = dict()
expr_to_output = dict()
swaps = dict()
carries = []
max_input_bit_index = -1
for line in lines:
if "->" in line:
expr, wire = line.split(" -> ")
left, op, right = expr.split(" ")
left, right = sorted((left, right))
output_to_expr[wire] = (left, right, op)
expr_to_output[(left, right, op)] = wire
if ":" in line:
max_input_bit_index = max(max_input_bit_index, int(line.split(":")[0][1:]))
num_input_bits = max_input_bit_index + 1
for i in range(num_input_bits):
z_output = f"z{i:02}"
input_xor_expr = (f"x{i:02}", f"y{i:02}", "XOR")
input_and_expr = (f"x{i:02}", f"y{i:02}", "AND")
input_xor_output = get_output_for_expr(input_xor_expr)
input_and_output = get_output_for_expr(input_and_expr)
if i == 0:
if z_output == input_xor_output:
carries.append(input_and_output)
continue
else:
raise ValueError("Error in first digits")
result_expr = find_matching_expr(input_xor_output, "XOR")
if result_expr == None:
result_expr = find_matching_expr(carries[i - 1], "XOR")
actual_input_xor_output = result_expr[1] if result_expr[0] == carries[i - 1] else result_expr[0]
swap(actual_input_xor_output, input_xor_output)
else:
carry_input = result_expr[1] if result_expr[0] == input_xor_output else result_expr[0]
if carry_input != carries[i - 1]:
swap(carry_input, carries[i - 1])
carries[i - 1] = carry_input
if z_output != get_output_for_expr(result_expr):
swap(z_output, get_output_for_expr(result_expr))
intermediate_carry_expr = (*sorted((get_output_for_expr(input_xor_expr), carries[i - 1])), "AND")
intermediate_carry_output = get_output_for_expr(intermediate_carry_expr)
carry_expr = find_matching_expr(intermediate_carry_output, "OR")
if carry_expr == None:
print("TODO")
else:
expected_input_and_output = carry_expr[1] if carry_expr[0] == intermediate_carry_output else carry_expr[0]
if expected_input_and_output != get_output_for_expr(input_and_expr):
swap(get_output_for_expr(input_and_expr), expected_input_and_output)
carry_expr = (*sorted((get_output_for_expr(input_and_expr), intermediate_carry_output)), "OR")
carry_output = get_output_for_expr(carry_expr)
carries.append(carry_output)
print(*sorted(swaps.keys()), sep=",") | python |
2024 | 24 | 2 | --- Day 24: Crossed Wires ---
You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently.
The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0).
AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0.
OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0.
XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0.
Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs.
Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example:
x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02
Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire).
The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00.
In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02.
Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on.
In this example, the three output bits form the binary number 100 which is equal to the decimal number 4.
Here's a larger example:
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
After waiting for values on all wires starting with z, the wires in this system have the following values:
bfw: 1
bqk: 1
djm: 1
ffh: 0
fgs: 1
frj: 1
fst: 1
gnj: 1
hwm: 1
kjc: 0
kpj: 1
kwq: 0
mjb: 1
nrd: 1
ntg: 0
pbm: 1
psh: 1
qhw: 1
rvg: 0
tgd: 0
tnw: 1
vdt: 1
wpb: 0
z00: 0
z01: 0
z02: 0
z03: 1
z04: 0
z05: 1
z06: 1
z07: 1
z08: 1
z09: 1
z10: 1
z11: 0
z12: 0
Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024.
Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?
Your puzzle answer was 52956035802096.
--- Part Two ---
After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers.
Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.)
The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z.
For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary):
x00: 1
x01: 1
x02: 0
x03: 1
y00: 1
y01: 0
y02: 1
y03: 1
If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000:
z00: 0
z01: 0
z02: 0
z03: 1
z04: 1
Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires.
Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.)
For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05:
x00: 0
x01: 1
x02: 0
x03: 1
x04: 0
x05: 1
y00: 0
y01: 0
y02: 1
y03: 1
y04: 0
y05: 1
x00 AND y00 -> z05
x01 AND y01 -> z02
x02 AND y02 -> z01
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z00
However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y:
x00 AND y00 -> z00
x01 AND y01 -> z01
x02 AND y02 -> z02
x03 AND y03 -> z03
x04 AND y04 -> z04
x05 AND y05 -> z05
In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05.
Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99.
Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas? | hnv,hth,kfm,tqr,vmv,z07,z20,z28 | #day 24
import os
from functools import cache
import re
from itertools import chain
def reader():
return open(f"24.txt", 'r').read().splitlines()
def part2():
f = '\n'.join(reader()).split('\n\n')
B = {}
for l in f[0].split('\n'):
v, b = l.split(': ')
B[v] = int(b)
F = {}
D = {}
for l in f[1].split('\n'):
f, v = l.split(' -> ')
v1, op, v2 = f.split(' ')
v1, v2 = sorted((v1, v2))
D[v] = {v1, v2}
op = {'XOR': '^', 'AND': '&', 'OR': '|'}[op]
F[v] = f"{v1} {op} {v2}"
for vv in [v, v1, v2]:
if vv not in B:
B[vv] = None
def swap(s1, s2):
F[s1], F[s2] = F[s2], F[s1]
D[s1], D[s2] = D[s2], D[s1]
# swap('z15', 'jgc')
# swap('z22', 'drg')
# swap('z35', 'jbp')
# swap('qjb', 'gvw')
def r(v):
if B[v] is None:
for dv in D[v]:
r(dv)
B[v] = eval(F[v], None, B)
return B[v]
def getNum(s): return int(''.join(map(lambda t: str(t[1]), sorted(
filter(lambda t: t[0][0] == s, B.items()), reverse=True))), base=2)
for v in B:
r(v)
@cache
def getFullFormula(v):
if v[0] in {'x', 'y'}:
return v
v1, op, v2 = F[v].split(' ')
v1, v2 = sorted((v1, v2))
return f"({getFullFormula(v1)}) {op} ({getFullFormula(v2)})"
FD = {}
for v in D:
formula = getFullFormula(v)
FD[v] = set(re.findall(r'x\d{2}|y\d{2}', formula))
problems = []
for i in range(1, len(list(filter(lambda t: t[0][0] == 'z', B.items()))) - 1):
p = f'((x{i:02}) ^ (y{i:02}))'
formula = getFullFormula(f'z{i:02}')
if f'{p} ^' not in formula and f'^ {p}' not in formula:
problems.append(i)
swaps = []
for p in problems:
x = f'x{p:02}'
y = f'y{p:02}'
z = f'z{p:02}'
start = f'{x} ^ {y}'
p1 = next(filter(lambda t: t[1] == start, F.items()))[0]
v1, op, v2 = F[z].split(' ')
if op != '^':
p2 = next(
filter(lambda t: f'^ {p1}' in t[1] or f'{p1} ^' in t[1], F.items()))[0]
swaps.append((z, p2))
else:
swaps.append(
(p1, sorted((v1, v2), key=lambda v: len(getFullFormula(v)))[0]))
print(','.join(sorted(chain(*swaps))))
part2() | python |
2024 | 25 | 1 | --- Day 25: Code Chronicle ---
Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing.
When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door.
Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input).
The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number.
"Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--" You explain that you need to open a door and don't have a lot of time.
"Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."
"The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."
He transmits you some example schematics:
#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####
"The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."
"For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."
"So, you could say the first lock has pin heights 0,5,3,4,3:"
#####
.####
.####
.####
.#.#.
.#...
.....
"Or, that the first key has heights 5,0,2,1,3:"
.....
#....
#....
#...#
#.#.#
#.###
#####
"These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."
"So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--" You disconnect the call.
In this example, converting both locks to pin heights produces:
0,5,3,4,3
1,2,0,5,3
Converting all three keys to heights produces:
5,0,2,1,3
4,3,4,0,2
3,0,2,0,1
Then, you can try every key with every lock:
Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column.
Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column.
Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit!
Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column.
Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit!
Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit!
So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3.
Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column? | 3162 | #!/usr/bin/env python3
myfile = open("25.in", "r")
lines = myfile.read().strip().split("\n\n")
myfile.close()
schematics = [line.split("\n") for line in lines]
part_one = 0
keys = set()
locks = set()
for schematic in schematics:
is_lock = schematic[0][0] == "#"
width = len(schematic[0])
cols = [[row[i] for row in schematic] for i in range(width)]
heights = tuple(c.count("#") - 1 for c in cols)
if is_lock:
locks.add(heights)
else:
keys.add(heights)
for lock in locks:
for key in keys:
max_key = tuple(5 - h for h in lock)
if all(h <= max_key[i] for i, h in enumerate(key)):
part_one += 1
print("Part One:", part_one) | python |
2024 | 25 | 1 | --- Day 25: Code Chronicle ---
Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing.
When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door.
Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input).
The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number.
"Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--" You explain that you need to open a door and don't have a lot of time.
"Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."
"The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."
He transmits you some example schematics:
#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####
"The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."
"For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."
"So, you could say the first lock has pin heights 0,5,3,4,3:"
#####
.####
.####
.####
.#.#.
.#...
.....
"Or, that the first key has heights 5,0,2,1,3:"
.....
#....
#....
#...#
#.#.#
#.###
#####
"These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."
"So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--" You disconnect the call.
In this example, converting both locks to pin heights produces:
0,5,3,4,3
1,2,0,5,3
Converting all three keys to heights produces:
5,0,2,1,3
4,3,4,0,2
3,0,2,0,1
Then, you can try every key with every lock:
Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column.
Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column.
Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit!
Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column.
Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit!
Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit!
So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3.
Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column? | 3162 | with open("./day_25.in") as fin:
lines = fin.read().strip().split("\n\n")
def parse(s):
lock = s[0][0] == "#"
if lock:
vals = []
for j in range(5):
for i in range(7):
if s[i][j] == ".":
vals.append(i)
break
return vals, lock
vals = []
for j in range(5):
for i in range(6, -1, -1):
if s[i][j] == ".":
vals.append(6 - i)
break
return vals, lock
locks = []
keys = []
for s in lines:
vals, lock = parse(s.split("\n"))
if lock:
locks.append(vals)
else:
keys.append(vals)
ans = 0
for lock in locks:
for key in keys:
good = True
for j in range(5):
if lock[j] + key[j] > 7:
good = False
break
ans += good
print(ans) | python |
2024 | 25 | 1 | --- Day 25: Code Chronicle ---
Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing.
When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door.
Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input).
The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number.
"Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--" You explain that you need to open a door and don't have a lot of time.
"Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."
"The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."
He transmits you some example schematics:
#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####
"The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."
"For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."
"So, you could say the first lock has pin heights 0,5,3,4,3:"
#####
.####
.####
.####
.#.#.
.#...
.....
"Or, that the first key has heights 5,0,2,1,3:"
.....
#....
#....
#...#
#.#.#
#.###
#####
"These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."
"So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--" You disconnect the call.
In this example, converting both locks to pin heights produces:
0,5,3,4,3
1,2,0,5,3
Converting all three keys to heights produces:
5,0,2,1,3
4,3,4,0,2
3,0,2,0,1
Then, you can try every key with every lock:
Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column.
Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column.
Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit!
Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column.
Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit!
Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit!
So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3.
Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column? | 3162 | import time
def parse(lines) -> set[tuple[int, int]]:
return {
(x, y)
for y, line in enumerate(lines)
for x, char in enumerate(line)
if char == "#"
}
def solve_part_1(text: str):
blocks = text.split("\n\n")
locks = []
keys = []
for b in blocks:
lines = b.splitlines()
schema = parse(lines[1:-1])
locks.append(schema) if lines[0] == "#####" else keys.append(schema)
r = 0
for lock in locks:
for key in keys:
r += len(lock & key) == 0
return r
def solve_part_2(text: str):
return 0
if __name__ == "__main__":
with open("input.txt", "r") as f:
quiz_input = f.read()
start = time.time()
p_1_solution = int(solve_part_1(quiz_input))
middle = time.time()
print(f"Part 1: {p_1_solution} (took {(middle - start) * 1000:.3f}ms)")
p_2_solution = int(solve_part_2(quiz_input))
end = time.time()
print(f"Part 2: {p_2_solution} (took {(end - middle) * 1000:.3f}ms)") | python |
2024 | 25 | 1 | --- Day 25: Code Chronicle ---
Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing.
When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door.
Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input).
The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number.
"Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--" You explain that you need to open a door and don't have a lot of time.
"Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."
"The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."
He transmits you some example schematics:
#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####
"The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."
"For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."
"So, you could say the first lock has pin heights 0,5,3,4,3:"
#####
.####
.####
.####
.#.#.
.#...
.....
"Or, that the first key has heights 5,0,2,1,3:"
.....
#....
#....
#...#
#.#.#
#.###
#####
"These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."
"So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--" You disconnect the call.
In this example, converting both locks to pin heights produces:
0,5,3,4,3
1,2,0,5,3
Converting all three keys to heights produces:
5,0,2,1,3
4,3,4,0,2
3,0,2,0,1
Then, you can try every key with every lock:
Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column.
Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column.
Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit!
Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column.
Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit!
Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit!
So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3.
Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column? | 3162 | locks = []
keys = []
with open("day25-data.txt") as file:
lines = file.readlines()
for i in range(0, len(lines), 8):
schematic = [line.strip('\n') for line in lines[i+1:i+6]]
schematic_transposed = [[schematic[j][i] for j in range(len(schematic))] for i in range(len(schematic[0]))]
pins = [a.count('#') for a in schematic_transposed]
if (lines[i] == "#####\n"):
locks.append(pins) # lock
elif lines[i] == ".....\n":
keys.append(pins) # key
sum = 0
for lock in locks:
for key in keys:
test = [lock[i] + key[i] for i in range(0, len(lock))]
if max(test) < 6:
sum += 1
print("Day 25 part 1, sum =", sum) | python |
2024 | 25 | 1 | --- Day 25: Code Chronicle ---
Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing.
When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door.
Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input).
The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number.
"Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--" You explain that you need to open a door and don't have a lot of time.
"Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."
"The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."
He transmits you some example schematics:
#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####
"The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."
"For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."
"So, you could say the first lock has pin heights 0,5,3,4,3:"
#####
.####
.####
.####
.#.#.
.#...
.....
"Or, that the first key has heights 5,0,2,1,3:"
.....
#....
#....
#...#
#.#.#
#.###
#####
"These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."
"So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--" You disconnect the call.
In this example, converting both locks to pin heights produces:
0,5,3,4,3
1,2,0,5,3
Converting all three keys to heights produces:
5,0,2,1,3
4,3,4,0,2
3,0,2,0,1
Then, you can try every key with every lock:
Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column.
Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column.
Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit!
Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column.
Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit!
Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit!
So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3.
Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column? | 3162 | import itertools
def get_lock(block):
col_counts = [5] * 5
for line in block[1:6]:
for i in range(5):
if line[i] == ".":
col_counts[i] -= 1
return col_counts
def get_key(block):
col_counts = [0] * 5
for line in block[1:6]:
for i in range(5):
if line[i] == "#":
col_counts[i] += 1
return col_counts
with open('input.txt') as f:
lines = f.read().splitlines()
locks = []
keys = []
for i in range(0, len(lines), 8):
block = lines[i:i+7]
if block[0][0] == "#":
locks.append(get_lock(block))
elif block[0][0] == ".":
keys.append(get_key(block))
ct_fit = sum([all([lock[i] + key[i] <= 5 for i in range(5)]) for lock, key in itertools.product(locks, keys)])
print(ct_fit) | python |
2024 | 22 | 1 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? | 15335183969 | data = open('input.txt').read().strip().split('\n')
def generateNextNumber(num):
res1 = num
temp = (num * 64)
res1 = (res1 ^ temp) % 16777216
res2 = res1
temp = (res1 // 32)
res2 = (res2 ^ temp) % 16777216
res3 = res2
temp = (res2 * 2048)
res3 = (res3 ^ temp) % 16777216
return res3
total = 0
for i in range(0, len(data)):
num = int(data[i])
for i in range(2000):
num = generateNextNumber(num)
total += num
print(total) | python |
2024 | 22 | 1 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? | 15335183969 | from typing import List
def parse_input(file_path: str) -> List[int]:
"""
Reads a file containing integers, one per line, and returns a list of these integers.
Args:
file_path (str): The path to the input file.
Returns:
List[int]: A list of integers read from the file.
"""
with open(file_path) as f:
return [int(line.strip()) for line in f]
def next_secret_number(secret: int) -> int:
"""
Calculate the next secret number based on the given secret number.
The function performs a series of bitwise operations and modular arithmetic
to generate a new secret number from the input secret number.
Steps:
1. Multiply the secret by 64, mix with XOR, and prune with modulo 16777216.
2. Divide the result by 32, mix with XOR, and prune with modulo 16777216.
3. Multiply the result by 2048, mix with XOR, and prune with modulo 16777216.
Args:
secret (int): The input secret number.
Returns:
int: The next secret number.
"""
# Step 1: Multiply by 64, mix, and prune
secret = (secret ^ (secret * 64)) % 16777216
# Step 2: Divide by 32, mix, and prune
secret = (secret ^ (secret // 32)) % 16777216
# Step 3: Multiply by 2048, mix, and prune
secret = (secret ^ (secret * 2048)) % 16777216
return secret
def generate_2000th_secret(initial_secret: int) -> int:
"""
Generates the 2000th secret number starting from the given initial secret.
Args:
initial_secret (int): The initial secret number to start from.
Returns:
int: The 2000th secret number.
"""
secret = initial_secret
for _ in range(2000):
secret = next_secret_number(secret)
return secret
if __name__ == "__main__":
input_data = parse_input('input.txt')
total = sum(generate_2000th_secret(secret) for secret in input_data)
print(total) | python |
2024 | 22 | 1 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? | 15335183969 | def step(num):
num = (num ^ (num * 64)) % 16777216
num = (num ^ (num // 32)) % 16777216
num = (num ^ (num * 2048)) % 16777216
return num
def process_buyers(file_path):
total = 0
with open(file_path) as file:
for line in file:
num = int(line)
buyer = [num % 10]
for _ in range(2000):
num = step(num)
buyer.append(num % 10)
total += num
return total
def main():
total = process_buyers("i.txt")
print(total)
if __name__ == "__main__":
main() | python |
2024 | 22 | 1 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? | 15335183969 | from collections import defaultdict
import numpy as np
with open("input.txt") as f:
ns = list(map(int, f.read().strip().split("\n")))
def hsh(secret):
for _ in range(2000):
secret ^= secret << 6 & 0xFFFFFF
secret ^= secret >> 5 & 0xFFFFFF
secret ^= secret << 11 & 0xFFFFFF
yield secret
secrets = list(map(list, map(hsh, ns)))
# Part 1
print(sum(s[-1] for s in secrets)) | python |
2024 | 22 | 1 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? | 15335183969 | def step(num):
num = (num ^ (num * 64)) % 16777216
num = (num ^ (num // 32)) % 16777216
num = (num ^ (num * 2048)) % 16777216
return num
def process_buyers(file_path):
total = 0
with open(file_path) as file:
for line in file:
num = int(line)
buyer = [num % 10]
for _ in range(2000):
num = step(num)
buyer.append(num % 10)
total += num
return total
def main():
total = process_buyers("22.txt")
print(total)
if __name__ == "__main__":
main() | python |
2024 | 22 | 2 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?
Your puzzle answer was 15335183969.
--- Part Two ---
Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers.
So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be:
3 (from 123)
0 (from 15887950)
6 (from 16495136)
5 (etc.)
4
4
6
4
4
2
This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf.
Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence.
So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be:
123: 3
15887950: 0 (-3)
16495136: 6 (6)
527345: 5 (-1)
704524: 4 (-1)
1553684: 4 (0)
12683156: 6 (2)
11100544: 4 (-2)
12249484: 4 (0)
7753432: 2 (-2)
Note that the first price has no associated change because there was no previous price to compare it with.
In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas.
Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer.
Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers.
You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur.
Suppose the initial secret number of each buyer is:
1
2
3
2024
There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales:
For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes.
For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9.
So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas!
Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get? | 1696 | from collections import defaultdict
import numpy as np
with open("input.txt") as f:
ns = list(map(int, f.read().strip().split("\n")))
def hsh(secret):
for _ in range(2000):
secret ^= secret << 6 & 0xFFFFFF
secret ^= secret >> 5 & 0xFFFFFF
secret ^= secret << 11 & 0xFFFFFF
yield secret
# Part 2
result = defaultdict(int)
for n in ns:
ss = [s % 10 for s in hsh(n)]
diffs = np.diff(ss)
changes = set()
for i in range(1996):
if (change := tuple(diffs[i : i + 4])) not in changes:
changes.add(change)
result[change] += ss[i + 4]
print(max(result.values())) | python |
2024 | 22 | 2 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?
Your puzzle answer was 15335183969.
--- Part Two ---
Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers.
So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be:
3 (from 123)
0 (from 15887950)
6 (from 16495136)
5 (etc.)
4
4
6
4
4
2
This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf.
Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence.
So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be:
123: 3
15887950: 0 (-3)
16495136: 6 (6)
527345: 5 (-1)
704524: 4 (-1)
1553684: 4 (0)
12683156: 6 (2)
11100544: 4 (-2)
12249484: 4 (0)
7753432: 2 (-2)
Note that the first price has no associated change because there was no previous price to compare it with.
In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas.
Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer.
Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers.
You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur.
Suppose the initial secret number of each buyer is:
1
2
3
2024
There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales:
For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes.
For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9.
So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas!
Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get? | 1696 | def step(num):
num = (num ^ (num * 64)) % 16777216
num = (num ^ (num // 32)) % 16777216
num = (num ^ (num * 2048)) % 16777216
return num
def process_buyers(file_path):
buyers = []
with open(file_path) as file:
for line in file:
num = int(line)
buyer = [num % 10]
for _ in range(2000):
num = step(num)
buyer.append(num % 10)
buyers.append(buyer)
return buyers
def calculate_sorok(buyers):
sorok = {}
for b in buyers:
seen = set()
for i in range(len(b) - 4):
a1, a2, a3, a4, a5 = b[i:i+5]
sor = (a2 - a1, a3 - a2, a4 - a3, a5 - a4)
if sor in seen:
continue
seen.add(sor)
if sor not in sorok:
sorok[sor] = 0
sorok[sor] += a5
return sorok
def main():
buyers = process_buyers("22.txt")
sorok = calculate_sorok(buyers)
print(max(sorok.values()))
if __name__ == "__main__":
main() | python |
2024 | 22 | 2 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?
Your puzzle answer was 15335183969.
--- Part Two ---
Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers.
So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be:
3 (from 123)
0 (from 15887950)
6 (from 16495136)
5 (etc.)
4
4
6
4
4
2
This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf.
Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence.
So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be:
123: 3
15887950: 0 (-3)
16495136: 6 (6)
527345: 5 (-1)
704524: 4 (-1)
1553684: 4 (0)
12683156: 6 (2)
11100544: 4 (-2)
12249484: 4 (0)
7753432: 2 (-2)
Note that the first price has no associated change because there was no previous price to compare it with.
In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas.
Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer.
Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers.
You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur.
Suppose the initial secret number of each buyer is:
1
2
3
2024
There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales:
For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes.
For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9.
So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas!
Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get? | 1696 | import time
N = 2000
def next_secret(s):
"""3-step pseudorandom transformation for a 24-bit integer."""
s = (s ^ ((s << 6) & 0xFFFFFF)) & 0xFFFFFF
s = (s ^ (s >> 5)) & 0xFFFFFF
s = (s ^ ((s << 11) & 0xFFFFFF)) & 0xFFFFFF
return s
def pack_diffs_into_key(d0, d1, d2, d3):
"""
Each diff is offset by +9 to fit into [0..18] (5 bits each).
Combine them into a single 20-bit integer.
"""
return (d0 << 15) | (d1 << 10) | (d2 << 5) | d3
def solve_part_2(text: str):
buyers = list(map(int, text.splitlines()))
size = 1 << 20 # total possible 4-diff combinations
seen = [0] * size
results = [0] * size
buyer_id = 1
secrets_arr = [0] * (N + 1)
prices_arr = [0] * (N + 1)
deltas_arr = [0] * (N + 1)
for secret_number in buyers:
# Fill arrays with generated secrets, prices, and deltas
secrets_arr[0] = secret_number
prices_arr[0] = secrets_arr[0] % 10
for i in range(1, N + 1):
secrets_arr[i] = next_secret(secrets_arr[i - 1])
prices_arr[i] = secrets_arr[i] % 10
deltas_arr[i] = prices_arr[i] - prices_arr[i - 1]
# From index 4 onward, we have a valid window of 4 consecutive deltas
for i in range(4, N + 1):
# We gather the 4 consecutive deltas leading to prices_arr[i].
d0 = deltas_arr[i - 3] + 9
d1 = deltas_arr[i - 2] + 9
d2 = deltas_arr[i - 1] + 9
d3 = deltas_arr[i] + 9
key = pack_diffs_into_key(d0, d1, d2, d3)
# Only record the first time this buyer sees this pattern
if seen[key] != buyer_id:
seen[key] = buyer_id
results[key] += prices_arr[i]
buyer_id += 1
return max(results)
if __name__ == "__main__":
with open("22.txt", "r") as f:
quiz_input = f.read()
p_2_solution = int(solve_part_2(quiz_input))
print(f"Part 2: {p_2_solution}") | python |
2024 | 22 | 2 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?
Your puzzle answer was 15335183969.
--- Part Two ---
Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers.
So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be:
3 (from 123)
0 (from 15887950)
6 (from 16495136)
5 (etc.)
4
4
6
4
4
2
This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf.
Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence.
So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be:
123: 3
15887950: 0 (-3)
16495136: 6 (6)
527345: 5 (-1)
704524: 4 (-1)
1553684: 4 (0)
12683156: 6 (2)
11100544: 4 (-2)
12249484: 4 (0)
7753432: 2 (-2)
Note that the first price has no associated change because there was no previous price to compare it with.
In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas.
Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer.
Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers.
You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur.
Suppose the initial secret number of each buyer is:
1
2
3
2024
There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales:
For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes.
For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9.
So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas!
Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get? | 1696 | import time, re, itertools as itt, collections as coll
def load(file):
with open(file) as f:
return map(int, re.findall('\d+', f.read()))
def mix_prune(s):
s = (s ^ (s * 64)) % 16777216
s = (s ^ (s // 32)) % 16777216
return (s ^ (s * 2048)) % 16777216
def solve(p):
part1 = part2 = 0
bananas = coll.defaultdict(int)
for s in p:
nums = [s := mix_prune(s) for _ in range(2000)]
diffs = [b % 10 - a % 10 for a, b in itt.pairwise(nums)]
first_seen_pat = set()
for i in range(len(nums) - 4):
pat = tuple(diffs[i:i + 4])
if pat in first_seen_pat: continue
bananas[pat] += nums[i + 4] % 10
first_seen_pat.add(pat)
part2 = max(bananas.values())
return part2
print(f'Solution: {solve(load("22.txt"))}') | python |
2024 | 22 | 2 | --- Day 22: Monkey Market ---
As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market.
You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets.
Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back.
On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell.
The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous.
In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process:
Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number.
Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number.
Each step of the above process involves mixing and pruning:
To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.)
To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.)
After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers.
So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be:
15887950
16495136
527345
704524
1553684
12683156
11100544
12249484
7753432
5908254
Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example:
1
10
100
2024
This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices.
In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are:
1: 8685429
10: 4700978
100: 15273692
2024: 8667524
Adding up the 2000th new secret number for each buyer produces 37327623.
For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?
Your puzzle answer was 15335183969.
--- Part Two ---
Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers.
So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be:
3 (from 123)
0 (from 15887950)
6 (from 16495136)
5 (etc.)
4
4
6
4
4
2
This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf.
Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence.
So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be:
123: 3
15887950: 0 (-3)
16495136: 6 (6)
527345: 5 (-1)
704524: 4 (-1)
1553684: 4 (0)
12683156: 6 (2)
11100544: 4 (-2)
12249484: 4 (0)
7753432: 2 (-2)
Note that the first price has no associated change because there was no previous price to compare it with.
In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas.
Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer.
Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers.
You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur.
Suppose the initial secret number of each buyer is:
1
2
3
2024
There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales:
For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7.
For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes.
For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9.
So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas!
Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get? | 1696 | with open("input.txt", "r") as file:
lines = file.readlines()
def secretStep(secret):
# Cleaned up
secret = (secret * 64 ^ secret) % 16777216
secret = (secret // 32 ^ secret) % 16777216
secret = (secret * 2048 ^ secret) % 16777216
return secret
# Custom implementation of max function
def findMax(sequence_totals):
max_key = None
max_value = float('-inf') # Start with the smallest possible value
for key, value in sequence_totals.items():
if value > max_value:
max_value = value
max_key = key
return max_key
def findMaxBananas(lines):
sequence_totals = {}
for line in lines:
secret_number = int(line)
price_list = [secret_number % 10] # Store last digit of secret numbers
# Generate 2000 price steps
for _ in range(2000):
secret_number = secretStep(secret_number)
price_list.append(secret_number % 10)
tracked_sequences = set()
# Examine all sequences of 4 consecutive price changes
for index in range(len(price_list) - 4):
p1, p2, p3, p4, p5 = price_list[index:index + 5] # Extract 5 consecutive prices
price_change = (p2 - p1, p3 - p2, p4 - p3, p5 - p4) # Calculate changes
if price_change in tracked_sequences: # Skip since we wont choose same again
continue
tracked_sequences.add(price_change)
if price_change not in sequence_totals:
sequence_totals[price_change] = 0
sequence_totals[price_change] += p5 # Add the price to the total
# Find highest total
# best_sequence = max(sequence_totals, key=sequence_totals.get)
best_sequence = findMax(sequence_totals)
max_bananas = sequence_totals[best_sequence]
return best_sequence, max_bananas
best_sequence, max_bananas = findMaxBananas(lines)
print(max_bananas) | python |
2024 | 20 | 1 | --- Day 20: Race Condition ---
The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU!
While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival!
The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex!
They hand you a map of the racetrack (your puzzle input). For example:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#).
When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds.
Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat.
The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified.
So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...12....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...12..#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 38 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.####1##.###
#...###.2.#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 64 picoseconds and takes the program directly to the end:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..21...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position.
In this example, the total number of cheats (grouped by the amount of time they save) are as follows:
There are 14 cheats that save 2 picoseconds.
There are 14 cheats that save 4 picoseconds.
There are 2 cheats that save 6 picoseconds.
There are 4 cheats that save 8 picoseconds.
There are 2 cheats that save 10 picoseconds.
There are 3 cheats that save 12 picoseconds.
There is one cheat that saves 20 picoseconds.
There is one cheat that saves 36 picoseconds.
There is one cheat that saves 38 picoseconds.
There is one cheat that saves 40 picoseconds.
There is one cheat that saves 64 picoseconds.
You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? | 1307 | import time
from enum import Enum
import heapq
file = open("20.txt", "r")
start_time = time.time()
class Direction(Enum):
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"{self.__dict__}"
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash(f"{self.x}_{self.y}")
@classmethod
def list(cls):
return list(map(lambda c: c.value, cls))
class TrackNode:
def __init__(self, position, order):
self.position = position
self.order = order
def __repr__(self):
return f"{self.__dict__}"
def __eq__(self, other):
return self.position == other.position and self.order == other.order
def __hash__(self):
return hash(f"{self.position}_{self.order}")
class Cheat:
def __init__(self, s, e):
self.s = s
self.e = e
def __repr__(self):
return f"{self.__dict__}"
def __eq__(self, other):
return self.s == other.s and self.e == other.e
def __hash__(self):
return hash(f"{self.s}_{self.e}")
space = 0
wall = 1
def import_matrix(matrix_string):
matrix = []
start_position = None
goal_position = None
for line_index, line in enumerate(matrix_string.split("\n")):
matrix.append([])
# print(line)
for column_index, tile in enumerate(line):
if tile == ".":
matrix[line_index].append(space)
elif tile == "#":
matrix[line_index].append(wall)
elif tile == "S":
matrix[line_index].append(space)
start_position = Position(column_index, line_index)
elif tile == "E":
matrix[line_index].append(space)
goal_position = Position(column_index, line_index)
return (matrix, start_position, goal_position)
map, start, goal = import_matrix(file.read())
def print_map(path = set()):
for line_index, line in enumerate(map):
string = []
for column_index, tile in enumerate(line):
if Position(column_index, line_index) == start:
string.append("S")
elif Position(column_index, line_index) == goal:
string.append("E")
elif Position(column_index, line_index) in path:
string.append("O")
elif tile == wall:
string.append("#")
else:
string.append(".")
print("".join(string))
def get_valid_in_direction(current_position, direction):
match direction:
case Direction.UP:
p = Position(current_position.x, current_position.y-1)
case Direction.LEFT:
p = Position(current_position.x-1, current_position.y)
case Direction.RIGHT:
p = Position(current_position.x+1, current_position.y)
case Direction.DOWN:
p = Position(current_position.x, current_position.y+1)
if p.x < 0 or p.x >= len(map[0]) or p.y < 0 or p.y >= len(map):
return None
return (p, direction)
def get_neighbors_and_cheats(current_position):
directions = [Direction.LEFT, Direction.RIGHT, Direction.UP, Direction.DOWN]
neighbors_in_map = [get_valid_in_direction(current_position, d) for d in directions]
neighbors = []
walls_with_direction = []
for n in neighbors_in_map:
if n is None:
continue
if map[n[0].y][n[0].x] == space:
neighbors.append(n[0])
else:
walls_with_direction.append(n)
cheats = []
for wd in walls_with_direction:
possible_cheat = get_valid_in_direction(wd[0], wd[1])
if possible_cheat is None:
continue
if map[possible_cheat[0].y][possible_cheat[0].x] == space:
cheats.append(Cheat(wd[0], possible_cheat[0]))
return (neighbors, cheats)
print("~~~~~~~~~~RESULT 1~~~~~~~~~~")
def create_track_1():
graph = {}
cheats_dict = {}
for line_index, line in enumerate(map):
for column_index, tile in enumerate(line):
if tile == wall:
continue
position = Position(column_index, line_index)
(neighbors, cheats) = get_neighbors_and_cheats(position)
graph[position] = neighbors
cheats_dict[position] = cheats
# track = {} # step: position
track = {} # position: step
cheats = {} # step: [Cheat]
ignore = set() # tracks what steps to ignore in track building; should contain whole path
current_position = start
current_step = 0
while True:
ignore.add(current_position)
# track[current_step] = current_position
track[current_position] = current_step
if current_position == goal:
break
# ignore already traversed track (backward cheat is not a cheat)
valid_cheats = [c for c in cheats_dict[current_position] if c.e not in ignore]
cheats[current_step] = valid_cheats
neighbors = graph[current_position]
# assuming only one valid path forward (or none if end)
for neighbor in neighbors:
if neighbor not in ignore: # ignore already traversed track
current_position = neighbor
continue
current_step += 1
return (track, cheats, current_step)
(track, cheats, total_steps) = create_track_1()
solution = 0
for step in cheats.keys():
for cheat in cheats[step]:
length_up_to_cheat = step
step_at_cheat_end = track[cheat.e]
resulting_length = length_up_to_cheat + 2 + (total_steps - step_at_cheat_end)
steps_saved = total_steps - resulting_length
if steps_saved >= 100:
solution += 1
print(solution) | python |
2024 | 20 | 1 | --- Day 20: Race Condition ---
The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU!
While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival!
The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex!
They hand you a map of the racetrack (your puzzle input). For example:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#).
When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds.
Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat.
The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified.
So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...12....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...12..#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 38 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.####1##.###
#...###.2.#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 64 picoseconds and takes the program directly to the end:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..21...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position.
In this example, the total number of cheats (grouped by the amount of time they save) are as follows:
There are 14 cheats that save 2 picoseconds.
There are 14 cheats that save 4 picoseconds.
There are 2 cheats that save 6 picoseconds.
There are 4 cheats that save 8 picoseconds.
There are 2 cheats that save 10 picoseconds.
There are 3 cheats that save 12 picoseconds.
There is one cheat that saves 20 picoseconds.
There is one cheat that saves 36 picoseconds.
There is one cheat that saves 38 picoseconds.
There is one cheat that saves 40 picoseconds.
There is one cheat that saves 64 picoseconds.
You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? | 1307 | grid = [[elem for elem in line.strip()] for line in open('input.txt')]
def get_start(grid):
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 'S':
return (i, j)
def get_end(grid):
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 'E':
return (i, j)
start = get_start(grid)
end = get_end(grid)
def get_neighbors(grid, pos):
i, j = pos
neighbors = []
if i > 0 and grid[i-1][j] != '#':
neighbors.append((i-1, j))
if i < len(grid) - 1 and grid[i+1][j] != '#':
neighbors.append((i+1, j))
if j > 0 and grid[i][j-1] != '#':
neighbors.append((i, j-1))
if j < len(grid[i]) - 1 and grid[i][j+1] != '#':
neighbors.append((i, j+1))
return neighbors
def get_race_track(grid, start, end):
visited = []
queue = [start]
while queue:
pos = queue.pop(0)
visited.append(pos)
if pos == end:
return visited
neighbors = get_neighbors(grid, pos)
for neighbor in neighbors:
if neighbor not in visited:
queue.append(neighbor)
return []
def print_path(grid, path):
grid_copy = [line.copy() for line in grid]
for pos in path[:10]:
i, j = pos
grid_copy[i][j] = 'X'
for line in grid_copy:
print(''.join(line))
def print_cheat(grid, first, second):
grid_copy = [line.copy() for line in grid]
grid_copy[first[0]][first[1]] = '1'
grid_copy[second[0]][second[1]] = '2'
for line in grid_copy:
print(''.join(line))
def get_cheats(path,grid):
cheats = {}
for i in range(len(path)):
for j in range(i,len(path)):
if (path[i][0] == path[j][0] and abs(path[i][1]-path[j][1]) == 2 and grid[path[i][0]][(path[i][1]+path[j][1])//2] == '#') or (path[i][1] == path[j][1] and abs(path[i][0]-path[j][0]) == 2 and grid[(path[i][0]+path[j][0])//2][path[i][1]] == '#'):
savedTime = j - i - 2
if savedTime not in cheats:
cheats[savedTime] = 1
else:
cheats[savedTime] += 1
return cheats
path = get_race_track(grid, start, end)
cheats = get_cheats(path,grid)
#rint(cheats)
count = 0
for key in cheats:
if key >= 100:
count += cheats[key]
print(count) | python |
2024 | 20 | 1 | --- Day 20: Race Condition ---
The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU!
While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival!
The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex!
They hand you a map of the racetrack (your puzzle input). For example:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#).
When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds.
Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat.
The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified.
So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...12....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...12..#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 38 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.####1##.###
#...###.2.#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 64 picoseconds and takes the program directly to the end:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..21...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position.
In this example, the total number of cheats (grouped by the amount of time they save) are as follows:
There are 14 cheats that save 2 picoseconds.
There are 14 cheats that save 4 picoseconds.
There are 2 cheats that save 6 picoseconds.
There are 4 cheats that save 8 picoseconds.
There are 2 cheats that save 10 picoseconds.
There are 3 cheats that save 12 picoseconds.
There is one cheat that saves 20 picoseconds.
There is one cheat that saves 36 picoseconds.
There is one cheat that saves 38 picoseconds.
There is one cheat that saves 40 picoseconds.
There is one cheat that saves 64 picoseconds.
You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? | 1307 | from collections import defaultdict, deque
from tqdm import tqdm
import copy
with open("./day_20.in") as fin:
grid = [list(line) for line in fin.read().strip().split("\n")]
N = len(grid)
def in_grid(i, j):
return 0 <= i < N and 0 <= j < N
for i in range(N):
for j in range(N):
if grid[i][j] == "S":
si, sj = i, j
elif grid[i][j] == "E":
ei, ej = i, j
dd = [[1, 0], [0, 1], [-1, 0], [0, -1]]
# Determine OG path
path = [(si, sj)]
while path[-1] != (ei, ej):
i, j = path[-1]
for di, dj in dd:
ii, jj = i + di, j + dj
if not in_grid(ii, jj):
continue
if len(path) > 1 and (ii, jj) == path[-2]:
continue
if grid[ii][jj] == "#":
continue
path.append((ii, jj))
break
og = len(path) - 1
times = {}
for t, coord in enumerate(path):
times[coord] = og - t
counts = defaultdict(int)
saved = {}
for t, coord in enumerate(tqdm(path, ncols=80)):
i, j = coord
for di1, dj1 in dd:
for di2, dj2 in dd:
ii, jj = i + di1 + di2, j + dj1 + dj2
if not in_grid(ii, jj) or grid[ii][jj] == "#":
continue
rem_t = times[(ii, jj)]
saved[(i, j, ii, jj)] = og - (t + rem_t + 2)
ans = 0
for v in saved.values():
if v >= 0: counts[v] += 1
if v >= 100: ans += 1
print(ans) | python |
2024 | 20 | 1 | --- Day 20: Race Condition ---
The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU!
While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival!
The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex!
They hand you a map of the racetrack (your puzzle input). For example:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#).
When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds.
Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat.
The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified.
So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...12....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...12..#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 38 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.####1##.###
#...###.2.#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 64 picoseconds and takes the program directly to the end:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..21...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position.
In this example, the total number of cheats (grouped by the amount of time they save) are as follows:
There are 14 cheats that save 2 picoseconds.
There are 14 cheats that save 4 picoseconds.
There are 2 cheats that save 6 picoseconds.
There are 4 cheats that save 8 picoseconds.
There are 2 cheats that save 10 picoseconds.
There are 3 cheats that save 12 picoseconds.
There is one cheat that saves 20 picoseconds.
There is one cheat that saves 36 picoseconds.
There is one cheat that saves 38 picoseconds.
There is one cheat that saves 40 picoseconds.
There is one cheat that saves 64 picoseconds.
You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? | 1307 | from collections import Counter
def find_shortcuts(map, p):
y, x = p
for direction in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
if in_direction(map, p, direction, 1) == '#':
shortcut_to = in_direction(map, p, direction, 2)
if shortcut_to == '#' or shortcut_to == '.':
continue
#print(f"Shortcut found from {p} to {shortcut_to}")
yield map[y][x] - shortcut_to - 2
def in_direction(map, f, d, count):
y = f[0]
x = f[1]
for _ in range(count):
y += d[0]
x += d[1]
if 0 > y or y >= len(map) or 0 > x or x >= len(map[0]):
return '#'
return map[y][x]
def step(map, p, steps):
y, x = p
for r, c in [(y+1,x), (y-1,x), (y,x+1), (y,x-1)]:
if map[r][c] == '.':
map[r][c] = steps
return (r, c)
map = []
with open('input') as input:
row = 0
for l in input:
l = l.strip()
map.append(list(l))
if 'S' in l:
start = (row, l.find('S'))
if 'E' in l:
end = (row, l.find('E'))
row += 1
print(f"Race from {start} to {end}")
p = start
shortcuts = []
steps = 0
map[start[0]][start[1]] = 0
map[end[0]][end[1]] = '.'
while p != end:
steps += 1
#print(f"Step {steps} from {p}")
shortcuts.extend(find_shortcuts(map, p))
p = step(map, p, steps)
# And also shortcuts straight to the end
shortcuts.extend(find_shortcuts(map, p))
for l, count in sorted(Counter(shortcuts).items(), key=lambda x: x[0]):
print(f"{l}: {count}")
print(sum(1 for s in shortcuts if s >= 100)) | python |
2024 | 20 | 1 | --- Day 20: Race Condition ---
The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU!
While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival!
The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex!
They hand you a map of the racetrack (your puzzle input). For example:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#).
When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds.
Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat.
The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified.
So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...12....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...12..#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 38 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.####1##.###
#...###.2.#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 64 picoseconds and takes the program directly to the end:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..21...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position.
In this example, the total number of cheats (grouped by the amount of time they save) are as follows:
There are 14 cheats that save 2 picoseconds.
There are 14 cheats that save 4 picoseconds.
There are 2 cheats that save 6 picoseconds.
There are 4 cheats that save 8 picoseconds.
There are 2 cheats that save 10 picoseconds.
There are 3 cheats that save 12 picoseconds.
There is one cheat that saves 20 picoseconds.
There is one cheat that saves 36 picoseconds.
There is one cheat that saves 38 picoseconds.
There is one cheat that saves 40 picoseconds.
There is one cheat that saves 64 picoseconds.
You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? | 1307 | from dataclasses import dataclass
from pathlib import Path
TEST = False
if TEST:
text = Path("20_test.txt").read_text().strip()
else:
text = Path("20.txt").read_text().strip()
grid = [list(l) for l in text.split("\n")]
width = len(grid[0])
height = len(grid)
def get_grid(p):
x = p.x
y = p.y
if x < 0 or x > width:
return None
if y < 0 or x > height:
return None
return grid[y][x]
@dataclass(frozen=True)
class Position:
x: int
y: int
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Position(x=x, y=y)
def manhattan_distance(self, other):
d_x = self.x - other.x
d_y = self.y - other.y
return abs(d_x) + abs(d_y)
def neighbours(position):
directions = [
Position(1, 0),
Position(-1, 0),
Position(0, 1),
Position(0, -1)
]
for d in directions:
new_position = position + d
if get_grid(new_position) == '.':
yield new_position
# Find the 'S', and the path from the 'S' to the 'E' - we're told there's a unique path.
for x in range(len(grid[0])):
for y in range(len(grid)):
p = Position(x=x, y=y)
if get_grid(p) == 'S':
start_position = p
grid[y][x] = '.'
elif get_grid(p) == 'E':
end_position = p
grid[y][x] = '.'
path = {start_position: 0}
last_position = start_position
while last_position != end_position:
next_ = [x for x in neighbours(last_position) if x not in path]
assert len(next_) == 1
next_ = next_[0]
path[next_] = len(path)
last_position = next_
# Part 1: How many jumps of length 2 save at least 100 picoseconds?
directions = [
Position(2, 0),
Position(-2, 0),
Position(0, 2),
Position(0, -2)
]
count = 0
for point in path:
for d in directions:
next_point = point + d
if next_point in path:
time_saved = path[next_point] - path[point] - 2
if time_saved >= 100:
count += 1
print(count) | python |
2024 | 20 | 2 | --- Day 20: Race Condition ---
The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU!
While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival!
The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex!
They hand you a map of the racetrack (your puzzle input). For example:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#).
When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds.
Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat.
The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified.
So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...12....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...12..#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 38 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.####1##.###
#...###.2.#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 64 picoseconds and takes the program directly to the end:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..21...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position.
In this example, the total number of cheats (grouped by the amount of time they save) are as follows:
There are 14 cheats that save 2 picoseconds.
There are 14 cheats that save 4 picoseconds.
There are 2 cheats that save 6 picoseconds.
There are 4 cheats that save 8 picoseconds.
There are 2 cheats that save 10 picoseconds.
There are 3 cheats that save 12 picoseconds.
There is one cheat that saves 20 picoseconds.
There is one cheat that saves 36 picoseconds.
There is one cheat that saves 38 picoseconds.
There is one cheat that saves 40 picoseconds.
There is one cheat that saves 64 picoseconds.
You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?
Your puzzle answer was 1307.
--- Part Two ---
The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds.
Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#1#####.#.#.###
#2#####.#.#...#
#3#####.#.###.#
#456.E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S12..#.#.#...#
###3###.#.#.###
###4###.#.#...#
###5###.#.###.#
###6.E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later.
You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more:
There are 32 cheats that save 50 picoseconds.
There are 31 cheats that save 52 picoseconds.
There are 29 cheats that save 54 picoseconds.
There are 39 cheats that save 56 picoseconds.
There are 25 cheats that save 58 picoseconds.
There are 23 cheats that save 60 picoseconds.
There are 20 cheats that save 62 picoseconds.
There are 19 cheats that save 64 picoseconds.
There are 12 cheats that save 66 picoseconds.
There are 14 cheats that save 68 picoseconds.
There are 12 cheats that save 70 picoseconds.
There are 22 cheats that save 72 picoseconds.
There are 4 cheats that save 74 picoseconds.
There are 3 cheats that save 76 picoseconds.
Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds? | 986545 | from collections import defaultdict
with open("input.txt") as input_file:
input_text = input_file.read().splitlines()
start = (-1, -1)
end = (-1, -1)
walls = set()
for row in range(len(input_text)):
for col in range(len(input_text[0])):
match input_text[row][col]:
case "S":
start = (row, col)
case "E":
end = (row, col)
case "#":
walls.add((row, col))
moves = ((1, 0), (-1, 0), (0, 1), (0, -1))
no_cheat_move_count = {start: 0}
current_pos = start
move_count = 0
while current_pos != end:
for row_move, col_move in moves:
new_pos = (current_pos[0] + row_move, current_pos[1] + col_move)
if new_pos not in walls and new_pos not in no_cheat_move_count:
move_count += 1
current_pos = new_pos
no_cheat_move_count[current_pos] = move_count
break
cheat_moves = []
for delta_row in range(-20, 21):
for delta_col in range(-(20 - abs(delta_row)), 21 - abs(delta_row)):
cheat_moves.append((delta_row, delta_col))
cheats = defaultdict(int)
for (initial_row, initial_col), step in no_cheat_move_count.items():
for row_move, col_move in cheat_moves:
cheat_pos = (initial_row + row_move, initial_col + col_move)
if no_cheat_move_count.get(cheat_pos, 0) > step + abs(row_move) + abs(col_move):
cheats[
no_cheat_move_count[cheat_pos] - step - abs(row_move) - abs(col_move)
] += 1
print(sum(count for saving, count in cheats.items() if saving >= 100)) | python |
2024 | 20 | 2 | --- Day 20: Race Condition ---
The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU!
While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival!
The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex!
They hand you a map of the racetrack (your puzzle input). For example:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#).
When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds.
Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat.
The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified.
So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...12....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...12..#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 38 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.####1##.###
#...###.2.#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 64 picoseconds and takes the program directly to the end:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..21...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position.
In this example, the total number of cheats (grouped by the amount of time they save) are as follows:
There are 14 cheats that save 2 picoseconds.
There are 14 cheats that save 4 picoseconds.
There are 2 cheats that save 6 picoseconds.
There are 4 cheats that save 8 picoseconds.
There are 2 cheats that save 10 picoseconds.
There are 3 cheats that save 12 picoseconds.
There is one cheat that saves 20 picoseconds.
There is one cheat that saves 36 picoseconds.
There is one cheat that saves 38 picoseconds.
There is one cheat that saves 40 picoseconds.
There is one cheat that saves 64 picoseconds.
You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?
Your puzzle answer was 1307.
--- Part Two ---
The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds.
Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#1#####.#.#.###
#2#####.#.#...#
#3#####.#.###.#
#456.E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S12..#.#.#...#
###3###.#.#.###
###4###.#.#...#
###5###.#.###.#
###6.E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later.
You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more:
There are 32 cheats that save 50 picoseconds.
There are 31 cheats that save 52 picoseconds.
There are 29 cheats that save 54 picoseconds.
There are 39 cheats that save 56 picoseconds.
There are 25 cheats that save 58 picoseconds.
There are 23 cheats that save 60 picoseconds.
There are 20 cheats that save 62 picoseconds.
There are 19 cheats that save 64 picoseconds.
There are 12 cheats that save 66 picoseconds.
There are 14 cheats that save 68 picoseconds.
There are 12 cheats that save 70 picoseconds.
There are 22 cheats that save 72 picoseconds.
There are 4 cheats that save 74 picoseconds.
There are 3 cheats that save 76 picoseconds.
Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds? | 986545 | def readfile(test_file):
file_name = "test.txt" if test_file else "input.txt"
with open(file_name) as f:
maze = [list(line.strip()) for line in f.readlines()]
start = (-1, -1)
end = (-1, -1)
# Create the maze with 1 as blocks and 0 as free
for r, row in enumerate(maze):
for c, _ in enumerate(row):
symbol = maze[r][c]
if symbol == "S":
# Keep track of start
start = (r, c)
maze[r][c] = 0
elif symbol == "E":
# Keep track of end
end = (r, c)
maze[r][c] = 0
elif symbol == ".":
maze[r][c] = 0
else:
maze[r][c] = 1
return maze, start, end
def part2(maze, start, end):
path, costs = cheapest_path(maze, start, end)
cheats = []
# Find all possible cheats with max duration of 20 picoseconds by pairwise matching of path
for i in range(0, len(path)):
for j in range(i, len(path)):
start = path[i]
end = path[j]
diff = abs(end[1] - start[1]) + abs(end[0] - start[0])
if 0 < diff <= 20:
cheats.append((start, end, diff))
time_saved = {}
# For each cheat keep track of how much time is saved
for cheat in cheats:
start = cheat[0]
end = cheat[1]
steps = cheat[2]
diff = costs[end] - costs[start] - steps
# Ignore cheats saving less than 100 picoseconds
if diff < 100:
continue
elif diff in time_saved:
time_saved[diff] += 1
else:
time_saved[diff] = 1
print(sum(time_saved.values()))
if __name__ == "__main__":
test_file = False
maze, start, end = readfile(test_file)
print("\nAnswer to part 2:")
part2(maze, start, end) | python |
2024 | 20 | 2 | --- Day 20: Race Condition ---
The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU!
While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival!
The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex!
They hand you a map of the racetrack (your puzzle input). For example:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#).
When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds.
Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat.
The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified.
So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...12....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...12..#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 38 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.####1##.###
#...###.2.#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 64 picoseconds and takes the program directly to the end:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..21...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position.
In this example, the total number of cheats (grouped by the amount of time they save) are as follows:
There are 14 cheats that save 2 picoseconds.
There are 14 cheats that save 4 picoseconds.
There are 2 cheats that save 6 picoseconds.
There are 4 cheats that save 8 picoseconds.
There are 2 cheats that save 10 picoseconds.
There are 3 cheats that save 12 picoseconds.
There is one cheat that saves 20 picoseconds.
There is one cheat that saves 36 picoseconds.
There is one cheat that saves 38 picoseconds.
There is one cheat that saves 40 picoseconds.
There is one cheat that saves 64 picoseconds.
You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?
Your puzzle answer was 1307.
--- Part Two ---
The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds.
Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#1#####.#.#.###
#2#####.#.#...#
#3#####.#.###.#
#456.E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S12..#.#.#...#
###3###.#.#.###
###4###.#.#...#
###5###.#.###.#
###6.E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later.
You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more:
There are 32 cheats that save 50 picoseconds.
There are 31 cheats that save 52 picoseconds.
There are 29 cheats that save 54 picoseconds.
There are 39 cheats that save 56 picoseconds.
There are 25 cheats that save 58 picoseconds.
There are 23 cheats that save 60 picoseconds.
There are 20 cheats that save 62 picoseconds.
There are 19 cheats that save 64 picoseconds.
There are 12 cheats that save 66 picoseconds.
There are 14 cheats that save 68 picoseconds.
There are 12 cheats that save 70 picoseconds.
There are 22 cheats that save 72 picoseconds.
There are 4 cheats that save 74 picoseconds.
There are 3 cheats that save 76 picoseconds.
Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds? | 986545 | with open("input20.txt") as i:
input = [x.strip() for x in i.readlines()]
test_data = """###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############""".split("\n")
# input = test_data
map = "".join(input)
w, h = len(input[0]), len(input)
start, end = map.index("S"), map.index("E")
def print_map():
for r in range(h):
print(map[r*w:(r+1)*w])
distances = [None]*w*h
working_set = [end]
current = 0
while len(working_set)>0:
next = []
for i in working_set:
if distances[i] is None:
distances[i] = current
next = [x for x in [i-1, i-w, i+1, i+w] if map[x]!="#" and distances[x] is None]
working_set = next
current += 1
original = distances[start]
def get_cheats(cheat_length, limit):
count = 0
for i in range(0, w*h):
if distances[i] is None: continue
for j in range(i+1, w*h):
if distances[j] is None: continue
x1, y1, x2, y2 = i%w, i//w, j%w, j//w
if abs(x1-x2) + abs(y1-y2)<=cheat_length:
k = 0
if distances[i] > distances[j]:
k = distances[start]-distances[i] + distances[j] + abs(x1-x2) + abs(y1-y2)
elif distances[i] < distances[j]:
k = distances[start]-distances[j] + distances[i] + abs(x1-x2) + abs(y1-y2)
if original-k>=limit:
count += 1
return count
print(get_cheats(20, 100)) | python |
2024 | 20 | 2 | --- Day 20: Race Condition ---
The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU!
While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival!
The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex!
They hand you a map of the racetrack (your puzzle input). For example:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#).
When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds.
Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat.
The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified.
So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...12....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...12..#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 38 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.####1##.###
#...###.2.#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 64 picoseconds and takes the program directly to the end:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..21...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position.
In this example, the total number of cheats (grouped by the amount of time they save) are as follows:
There are 14 cheats that save 2 picoseconds.
There are 14 cheats that save 4 picoseconds.
There are 2 cheats that save 6 picoseconds.
There are 4 cheats that save 8 picoseconds.
There are 2 cheats that save 10 picoseconds.
There are 3 cheats that save 12 picoseconds.
There is one cheat that saves 20 picoseconds.
There is one cheat that saves 36 picoseconds.
There is one cheat that saves 38 picoseconds.
There is one cheat that saves 40 picoseconds.
There is one cheat that saves 64 picoseconds.
You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?
Your puzzle answer was 1307.
--- Part Two ---
The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds.
Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#1#####.#.#.###
#2#####.#.#...#
#3#####.#.###.#
#456.E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S12..#.#.#...#
###3###.#.#.###
###4###.#.#...#
###5###.#.###.#
###6.E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later.
You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more:
There are 32 cheats that save 50 picoseconds.
There are 31 cheats that save 52 picoseconds.
There are 29 cheats that save 54 picoseconds.
There are 39 cheats that save 56 picoseconds.
There are 25 cheats that save 58 picoseconds.
There are 23 cheats that save 60 picoseconds.
There are 20 cheats that save 62 picoseconds.
There are 19 cheats that save 64 picoseconds.
There are 12 cheats that save 66 picoseconds.
There are 14 cheats that save 68 picoseconds.
There are 12 cheats that save 70 picoseconds.
There are 22 cheats that save 72 picoseconds.
There are 4 cheats that save 74 picoseconds.
There are 3 cheats that save 76 picoseconds.
Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds? | 986545 | from collections import defaultdict
import heapq
def parse_input(filename):
grid = []
with open(filename, 'r') as file:
for line in file:
line = line.strip()
grid.append([char for char in line])
return grid
def solve1(grid, minsave):
si, sj, ei, ej = 0,0,0,0
N, M = len(grid), len(grid[0])
def inside(i,j):
return 0<=i<N and 0<=j<M
for i in range(N):
for j in range(M):
if grid[i][j] == 'S':
si, sj = i, j
elif grid[i][j] == 'E':
ei, ej = i, j
h = [(0, si, sj, 0, 0)]
path = []
cost = {}
while h:
c, i, j, pi, pj = h.pop()
if grid[i][j] == "#":
continue
else:
path.append((i,j))
cost[(i,j)] = c
if grid[i][j] == "E": break
nxt = [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]
for ni, nj in nxt:
if (ni,nj) == (pi,pj): continue
h.append((c+1, ni,nj,i,j))
savings = {}
count = 0
for i,j in path:
nxt = [(i+2,j),(i-2,j),(i,j+2),(i,j-2)]
thru = [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]
for x in range(len(nxt)):
ni,nj = nxt[x]
ti,tj = thru[x]
if not inside(ni,nj) or grid[ni][nj] == '#':
continue
if cost[(ni,nj)] - cost[(i,j)] - 2 >= minsave and grid[ti][tj] == '#':
savings[(i,j,ni,nj)] = cost[(ni,nj)] - cost[(i,j)] - 2
count += 1
print(f"Part One - {count}") # 1518
def solve2(grid, minsave):
si, sj, ei, ej = 0,0,0,0
N, M = len(grid), len(grid[0])
def inside(i,j):
return 0<=i<N and 0<=j<M
for i in range(N):
for j in range(M):
if grid[i][j] == 'S':
si, sj = i, j
elif grid[i][j] == 'E':
ei, ej = i, j
h = [(0, si, sj, 0, 0)]
path = []
cost = {}
while h:
c, i, j, pi, pj = h.pop()
if grid[i][j] == "#":
continue
else:
path.append((i,j))
cost[(i,j)] = c
if grid[i][j] == "E": break
nxt = [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]
for ni, nj in nxt:
if (ni,nj) == (pi,pj): continue
h.append((c+1, ni,nj,i,j))
savings = {}
count = 0
for i,j in path:
for step in range(2, 21): # step as manhatten distance
for di in range(step+1):
dj = step - di
nxt = [(i+di,j+dj),(i+di,j-dj),(i-di,j+dj),(i-di,j-dj)]
for x in range(len(nxt)):
ni,nj = nxt[x]
if not inside(ni,nj) or grid[ni][nj] == '#' or (i,j,ni,nj) in savings:
continue
if cost[(ni,nj)] - cost[(i,j)] - step >= minsave:
savings[(i,j,ni,nj)] = cost[(ni,nj)] - cost[(i,j)] - step
count += 1
print(f"Part Two - {count}") # 1032257
# grid = parse_input('./inputs/day20toy.txt')
# solve1(grid, 0)
# solve2(grid, 50)
grid = parse_input('./inputs/day20.txt')
solve1(grid, 100)
solve2(grid, 100) | python |
2024 | 20 | 2 | --- Day 20: Race Condition ---
The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU!
While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival!
The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex!
They hand you a map of the racetrack (your puzzle input). For example:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#).
When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds.
Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat.
The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified.
So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...12....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...12..#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 38 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.####1##.###
#...###.2.#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
This cheat saves 64 picoseconds and takes the program directly to the end:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..21...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position.
In this example, the total number of cheats (grouped by the amount of time they save) are as follows:
There are 14 cheats that save 2 picoseconds.
There are 14 cheats that save 4 picoseconds.
There are 2 cheats that save 6 picoseconds.
There are 4 cheats that save 8 picoseconds.
There are 2 cheats that save 10 picoseconds.
There are 3 cheats that save 12 picoseconds.
There is one cheat that saves 20 picoseconds.
There is one cheat that saves 36 picoseconds.
There is one cheat that saves 38 picoseconds.
There is one cheat that saves 40 picoseconds.
There is one cheat that saves 64 picoseconds.
You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?
Your puzzle answer was 1307.
--- Part Two ---
The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds.
Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#1#####.#.#.###
#2#####.#.#...#
#3#####.#.###.#
#456.E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different:
###############
#...#...#.....#
#.#.#.#.#.###.#
#S12..#.#.#...#
###3###.#.#.###
###4###.#.#...#
###5###.#.###.#
###6.E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later.
You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more:
There are 32 cheats that save 50 picoseconds.
There are 31 cheats that save 52 picoseconds.
There are 29 cheats that save 54 picoseconds.
There are 39 cheats that save 56 picoseconds.
There are 25 cheats that save 58 picoseconds.
There are 23 cheats that save 60 picoseconds.
There are 20 cheats that save 62 picoseconds.
There are 19 cheats that save 64 picoseconds.
There are 12 cheats that save 66 picoseconds.
There are 14 cheats that save 68 picoseconds.
There are 12 cheats that save 70 picoseconds.
There are 22 cheats that save 72 picoseconds.
There are 4 cheats that save 74 picoseconds.
There are 3 cheats that save 76 picoseconds.
Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds? | 986545 | #!/usr/bin/env python3
from collections import defaultdict, deque
myfile = open("20.txt", "r")
lines = myfile.read().strip().splitlines()
myfile.close()
end = start = (-1, -1)
grid = defaultdict(str)
for y in range(len(lines)):
for x in range(len(lines[y])):
if lines[y][x] == "S":
start = (x, y)
elif lines[y][x] == "E":
end = (x, y)
grid[(x, y)] = lines[y][x]
part_one = 0
part_two = 0
visited = set()
scores = defaultdict(lambda: float("inf"))
scores[start] = 0
q = deque([start])
while q:
pos = q.popleft()
visited.add(pos)
for dir in [(1, 0), (0, -1), (-1, 0), (0, 1)]:
next_pos = (pos[0] + dir[0], pos[1] + dir[1])
if next_pos not in visited and grid[next_pos] != "#" and grid[next_pos] != "":
scores[next_pos] = scores[pos] + 1
q.append(next_pos)
for a in visited:
for i in range(-20, 21):
for j in range(-20, 21):
dist = abs(i) + abs(j)
if dist > 20:
continue
b = (a[0] + i, a[1] + j)
if b not in visited:
continue
savings = scores[b] - scores[a] - dist
if savings < 100:
continue
if dist <= 2:
part_one += 1
part_two += 1
print("Part One:", part_one)
print("Part Two:", part_two) | python |
2024 | 1 | 1 | --- Day 1: Historian Hysteria ---
The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit.
As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office.
Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search?
Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs.
There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists?
For example:
3 4
4 3
2 5
1 3
3 9
3 3
Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on.
Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6.
In the example list above, the pairs and distances would be as follows:
The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2.
The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1.
The third-smallest number in both lists is 3, so the distance between them is 0.
The next numbers to pair up are 3 and 4, a distance of 1.
The fifth-smallest numbers in each list are 3 and 5, a distance of 2.
Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart.
To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11!
Your actual left and right lists contain many location IDs. What is the total distance between your lists? | 2378066 | const fs = require('fs');
// Read the input file, validate file
const data = fs.readFileSync('input.txt', 'utf8');
// Parse the input data
const lines = data.trim().split('\n');
let leftList = [];
let rightList = [];
lines.forEach(line => {
const [left, right] = line.split(/\s+/).map(Number);
leftList.push(left);
rightList.push(right);
});
// Sort both lists
leftList.sort((a, b) => a - b);
rightList.sort((a, b) => a - b);
// Calculate the absolute distance
let totalDistance = 0;
for (let i = 0; i < leftList.length; i++) {
totalDistance += Math.abs(leftList[i] - rightList[i]);
}
console.log('Total Distance:', totalDistance); | javascript |
2024 | 1 | 1 | --- Day 1: Historian Hysteria ---
The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit.
As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office.
Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search?
Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs.
There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists?
For example:
3 4
4 3
2 5
1 3
3 9
3 3
Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on.
Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6.
In the example list above, the pairs and distances would be as follows:
The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2.
The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1.
The third-smallest number in both lists is 3, so the distance between them is 0.
The next numbers to pair up are 3 and 4, a distance of 1.
The fifth-smallest numbers in each list are 3 and 5, a distance of 2.
Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart.
To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11!
Your actual left and right lists contain many location IDs. What is the total distance between your lists? | 2378066 | const fs = require("fs");
let buffer, input, rows;
try {
buffer = fs.readFileSync(__dirname + "/input.txt", "utf8");
} catch (e) {
throw e;
}
input = buffer.toString();
rows = input.split("\n");
const left_list = [];
const right_list = [];
rows.forEach((row) => {
if (row === "") {
return;
}
const nums = row.split(" ");
left_list.push(Number(nums[0]));
right_list.push(Number(nums[1]));
});
left_list.sort();
right_list.sort();
const total_distance = left_list.reduce((accumulator, item, index) => {
return accumulator + Math.abs(right_list[index] - item);
}, 0);
console.log({ total_distance }); | javascript |
2024 | 1 | 1 | --- Day 1: Historian Hysteria ---
The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit.
As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office.
Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search?
Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs.
There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists?
For example:
3 4
4 3
2 5
1 3
3 9
3 3
Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on.
Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6.
In the example list above, the pairs and distances would be as follows:
The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2.
The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1.
The third-smallest number in both lists is 3, so the distance between them is 0.
The next numbers to pair up are 3 and 4, a distance of 1.
The fifth-smallest numbers in each list are 3 and 5, a distance of 2.
Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart.
To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11!
Your actual left and right lists contain many location IDs. What is the total distance between your lists? | 2378066 | const fs = require('fs');
const input = fs.readFileSync('./input.txt', 'utf8').trim().split('\n');
const leftList = [];
const rightList = [];
input.forEach(line => {
const [left, right] = line.split(' ').map(Number);
leftList.push(left);
rightList.push(right);
});
// Part 1
function calculateTotalDistance(leftList, rightList) {
const sortedLeft = [...leftList].sort((a, b) => a - b);
const sortedRight = [...rightList].sort((a, b) => a - b);
let totalDistance = 0;
for (let i = 0; i < sortedLeft.length; i++) {
totalDistance += Math.abs(sortedLeft[i] - sortedRight[i]);
}
return totalDistance;
}
// Part 2
function calculateSimilarityScore(leftList, rightList) {
const frequencyMap = new Map();
rightList.forEach(num => {
frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1);
});
let similarityScore = 0;
leftList.forEach(num => {
const count = frequencyMap.get(num) || 0;
similarityScore += num * count;
});
return similarityScore;
}
const totalDistance = calculateTotalDistance(leftList, rightList);
console.log('Part 1 - Total Distance:', totalDistance);
const similarityScore = calculateSimilarityScore(leftList, rightList);
console.log('Part 2 - Similarity Score:', similarityScore); | javascript |
2024 | 1 | 1 | --- Day 1: Historian Hysteria ---
The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit.
As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office.
Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search?
Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs.
There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists?
For example:
3 4
4 3
2 5
1 3
3 9
3 3
Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on.
Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6.
In the example list above, the pairs and distances would be as follows:
The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2.
The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1.
The third-smallest number in both lists is 3, so the distance between them is 0.
The next numbers to pair up are 3 and 4, a distance of 1.
The fifth-smallest numbers in each list are 3 and 5, a distance of 2.
Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart.
To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11!
Your actual left and right lists contain many location IDs. What is the total distance between your lists?
Your puzzle answer was 2378066.
--- Part Two ---
Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different.
Or are they?
The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting.
This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list.
Here are the same example lists again:
3 4
4 3
2 5
1 3
3 9
3 3
For these example lists, here is the process of finding the similarity score:
The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9.
The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4.
The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0).
The fourth number, 1, also does not appear in the right list.
The fifth number, 3, appears in the right list three times; the similarity score increases by 9.
The last number, 3, appears in the right list three times; the similarity score again increases by 9.
So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9).
Once again consider your left and right lists. What is their similarity score? | 2378066 | const fs = require('fs');
// Function to calculate total distance between two lists
function calculateTotalDistance(leftList, rightList) {
// Sort both lists in ascending order
leftList.sort((a, b) => a - b);
rightList.sort((a, b) => a - b);
// Calculate the distances and sum them up
let totalDistance = 0;
for (let i = 0; i < leftList.length; i++) {
totalDistance += Math.abs(leftList[i] - rightList[i]);
}
return totalDistance;
}
// Read the input file
fs.readFile('input.txt', 'utf-8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
// Split the input into lines and parse the two lists
const lines = data.trim().split('\n');
const leftList = [];
const rightList = [];
lines.forEach(line => {
const [left, right] = line.split(/\s+/).map(Number); // Split and convert to numbers
leftList.push(left);
rightList.push(right);
});
// Calculate the total distance
const totalDistance = calculateTotalDistance(leftList, rightList);
// Output the result
console.log('Total Distance:', totalDistance);
}); | javascript |
2024 | 1 | 1 | --- Day 1: Historian Hysteria ---
The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit.
As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office.
Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search?
Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs.
There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists?
For example:
3 4
4 3
2 5
1 3
3 9
3 3
Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on.
Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6.
In the example list above, the pairs and distances would be as follows:
The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2.
The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1.
The third-smallest number in both lists is 3, so the distance between them is 0.
The next numbers to pair up are 3 and 4, a distance of 1.
The fifth-smallest numbers in each list are 3 and 5, a distance of 2.
Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart.
To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11!
Your actual left and right lists contain many location IDs. What is the total distance between your lists? | 2378066 | let fs = require('fs');
let puzzleInput = fs.readFileSync('input.txt').toString().split("\n");
let firstLocations = [];
let secondLocations = [];
puzzleInput.forEach((line) => {
let parseLine = line.split(' ');
if (parseLine[0] != '') firstLocations.push(parseLine[0]);
if (parseLine[1] != '') secondLocations.push(parseLine[1]);
});
let sortedFirstLocations = firstLocations.sort();
let sortedSecondLocations = secondLocations.sort();
let accumulatedDistance = 0;
sortedFirstLocations.forEach((location, index) => {
let difference = location - sortedSecondLocations[index];
if (difference < 0) {
difference = difference * -1;
}
accumulatedDistance += difference;
});
console.log(accumulatedDistance); | javascript |
2024 | 1 | 2 | --- Day 1: Historian Hysteria ---
The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit.
As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office.
Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search?
Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs.
There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists?
For example:
3 4
4 3
2 5
1 3
3 9
3 3
Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on.
Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6.
In the example list above, the pairs and distances would be as follows:
The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2.
The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1.
The third-smallest number in both lists is 3, so the distance between them is 0.
The next numbers to pair up are 3 and 4, a distance of 1.
The fifth-smallest numbers in each list are 3 and 5, a distance of 2.
Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart.
To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11!
Your actual left and right lists contain many location IDs. What is the total distance between your lists?
Your puzzle answer was 2378066.
--- Part Two ---
Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different.
Or are they?
The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting.
This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list.
Here are the same example lists again:
3 4
4 3
2 5
1 3
3 9
3 3
For these example lists, here is the process of finding the similarity score:
The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9.
The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4.
The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0).
The fourth number, 1, also does not appear in the right list.
The fifth number, 3, appears in the right list three times; the similarity score increases by 9.
The last number, 3, appears in the right list three times; the similarity score again increases by 9.
So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9).
Once again consider your left and right lists. What is their similarity score? | 18934359 | const fs = require("fs");
const path = require("path");
const fileTxt = fs.readFileSync(path.join(__dirname, "input.txt"));
const inputFromAdvent = fileTxt.toString();
const parseInput = (input) => {
const parsedInput = input
.trim()
.split("\n")
.reduce(
(acc, item) => {
const [first, second] = item.split(" ").filter(Boolean);
acc[0].push(Number(first));
acc[1].push(Number(second));
return acc;
},
[[], []]
);
return parsedInput;
};
const orderLists = (input) => {
const [first, second] = input;
const orderedFirst = first.sort((a, b) => a - b);
const orderedSecond = second.sort((a, b) => a - b);
return [orderedFirst, orderedSecond];
};
const getDistance = (input) => {
const distanceArray = [];
const [first, second] = orderLists(input);
for (let i = 0; i < first.length; i++) {
distanceArray.push(Math.abs(first[i] - second[i]));
}
return distanceArray;
};
const sumDistance = (input) => {
return input.reduce((acc, item) => acc + item, 0);
};
const getTotalDistance = (input) => {
const [arrayA, arrayB] = input
.trim()
.split("\n")
.reduce(
(acc, line) => {
const [a, b] = line.match(/\S+/g).map(Number);
acc[0].push(a);
acc[1].push(b);
return acc;
},
[[], []]
);
arrayA.sort((a, b) => a - b);
arrayB.sort((a, b) => a - b);
return arrayA.reduce((total, a, index) => {
return total + Math.abs(a - arrayB[index]);
}, 0);
};
const main1 = () => {
console.log(getTotalDistance(inputFromAdvent));
};
const getTotalSimilarity = (input) => {
const [arrayA, arrayB] = parseInput(input);
return arrayA.reduce((total, arrayAItem) => {
return (
total +
arrayB.filter((arrayBItem) => arrayBItem === arrayAItem).length *
arrayAItem
);
}, 0);
};
const main2 = () => {
console.log(getTotalSimilarity(inputFromAdvent));
};
module.exports = {
parseInput,
orderLists,
getDistance,
sumDistance,
getTotalDistance,
getTotalSimilarity,
};
// main1();
main2(); | javascript |
2024 | 1 | 2 | --- Day 1: Historian Hysteria ---
The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit.
As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office.
Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search?
Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs.
There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists?
For example:
3 4
4 3
2 5
1 3
3 9
3 3
Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on.
Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6.
In the example list above, the pairs and distances would be as follows:
The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2.
The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1.
The third-smallest number in both lists is 3, so the distance between them is 0.
The next numbers to pair up are 3 and 4, a distance of 1.
The fifth-smallest numbers in each list are 3 and 5, a distance of 2.
Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart.
To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11!
Your actual left and right lists contain many location IDs. What is the total distance between your lists?
Your puzzle answer was 2378066.
--- Part Two ---
Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different.
Or are they?
The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting.
This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list.
Here are the same example lists again:
3 4
4 3
2 5
1 3
3 9
3 3
For these example lists, here is the process of finding the similarity score:
The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9.
The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4.
The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0).
The fourth number, 1, also does not appear in the right list.
The fifth number, 3, appears in the right list three times; the similarity score increases by 9.
The last number, 3, appears in the right list three times; the similarity score again increases by 9.
So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9).
Once again consider your left and right lists. What is their similarity score? | 18934359 | const fs = require("fs");
const inputText = "./input.txt";
fs.readFile(inputText, "utf8", (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
data = data.split(/\s+/);
const lists = [[], []];
for (let i = 0; i < data.length; i++) {
lists[i % 2].push(Number(data[i]));
}
console.log(part1(lists));
console.log(part2(lists));
});
const part1 = (lists) => {
lists = lists.map(list => list.sort());
return lists[0].reduce((acc, curr, index) => {
const diff = Math.abs(lists[1][index] - curr);
return acc + diff;
}, 0);
}
const part2 = (lists) => {
let similarityScore = 0;
lists[0].forEach(num => {
similarityScore += (lists[1].filter(item => item === num).length * num);
})
return similarityScore;
} | javascript |
2024 | 1 | 2 | --- Day 1: Historian Hysteria ---
The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit.
As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office.
Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search?
Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs.
There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists?
For example:
3 4
4 3
2 5
1 3
3 9
3 3
Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on.
Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6.
In the example list above, the pairs and distances would be as follows:
The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2.
The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1.
The third-smallest number in both lists is 3, so the distance between them is 0.
The next numbers to pair up are 3 and 4, a distance of 1.
The fifth-smallest numbers in each list are 3 and 5, a distance of 2.
Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart.
To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11!
Your actual left and right lists contain many location IDs. What is the total distance between your lists?
Your puzzle answer was 2378066.
--- Part Two ---
Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different.
Or are they?
The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting.
This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list.
Here are the same example lists again:
3 4
4 3
2 5
1 3
3 9
3 3
For these example lists, here is the process of finding the similarity score:
The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9.
The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4.
The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0).
The fourth number, 1, also does not appear in the right list.
The fifth number, 3, appears in the right list three times; the similarity score increases by 9.
The last number, 3, appears in the right list three times; the similarity score again increases by 9.
So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9).
Once again consider your left and right lists. What is their similarity score? | 18934359 | const fs = require('fs');
const input = fs.readFileSync('input.txt', 'utf8');
const lines = input.split('\n');
const leftNumbers = [];
const rightNumbers = [];
let similarityScore = 0;
lines.forEach((line) => {
const [left, right] = line.trim().split(/\s+/).map(Number);
leftNumbers.push(left);
rightNumbers.push(right);
});
for (let i = 0; i < leftNumbers.length; i++) {
let counter = rightNumbers.filter((x) => x == leftNumbers[i]).length;
similarityScore += counter * leftNumbers[i];
}
console.log(similarityScore); | javascript |
2024 | 1 | 2 | --- Day 1: Historian Hysteria ---
The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit.
As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office.
Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search?
Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs.
There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists?
For example:
3 4
4 3
2 5
1 3
3 9
3 3
Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on.
Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6.
In the example list above, the pairs and distances would be as follows:
The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2.
The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1.
The third-smallest number in both lists is 3, so the distance between them is 0.
The next numbers to pair up are 3 and 4, a distance of 1.
The fifth-smallest numbers in each list are 3 and 5, a distance of 2.
Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart.
To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11!
Your actual left and right lists contain many location IDs. What is the total distance between your lists?
Your puzzle answer was 2378066.
--- Part Two ---
Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different.
Or are they?
The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting.
This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list.
Here are the same example lists again:
3 4
4 3
2 5
1 3
3 9
3 3
For these example lists, here is the process of finding the similarity score:
The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9.
The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4.
The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0).
The fourth number, 1, also does not appear in the right list.
The fifth number, 3, appears in the right list three times; the similarity score increases by 9.
The last number, 3, appears in the right list three times; the similarity score again increases by 9.
So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9).
Once again consider your left and right lists. What is their similarity score? | 18934359 | const fs = require("fs");
let input = fs.readFileSync("input.txt", "utf-8");
input = input.split(/\r?\n/).map((row) => row.split(" "));
const firstCol = input.map((row) => row[0]);
const secondCol = input.map((row) => row[1]);
const firstSolution = () => {
const firstColSorted = firstCol.sort();
const secondColSorted = secondCol.sort();
const distances = firstColSorted.map((firstColValue, index) =>
Math.abs(firstColValue - secondColSorted[index])
);
return distances.reduce((acc, value) => acc + value, 0);
};
console.log("first part result:", firstSolution());
const secondSolution = () => {
const similarity = firstCol.map(
(firstColValue) =>
firstColValue *
secondCol.filter((secondColValue) => secondColValue === firstColValue)
.length
);
return similarity.reduce((acc, value) => acc + value, 0);
};
console.log("second part result:", secondSolution()); | javascript |
2024 | 1 | 2 | --- Day 1: Historian Hysteria ---
The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit.
As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office.
Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search?
Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs.
There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists?
For example:
3 4
4 3
2 5
1 3
3 9
3 3
Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on.
Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6.
In the example list above, the pairs and distances would be as follows:
The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2.
The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1.
The third-smallest number in both lists is 3, so the distance between them is 0.
The next numbers to pair up are 3 and 4, a distance of 1.
The fifth-smallest numbers in each list are 3 and 5, a distance of 2.
Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart.
To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11!
Your actual left and right lists contain many location IDs. What is the total distance between your lists?
Your puzzle answer was 2378066.
--- Part Two ---
Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different.
Or are they?
The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting.
This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list.
Here are the same example lists again:
3 4
4 3
2 5
1 3
3 9
3 3
For these example lists, here is the process of finding the similarity score:
The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9.
The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4.
The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0).
The fourth number, 1, also does not appear in the right list.
The fifth number, 3, appears in the right list three times; the similarity score increases by 9.
The last number, 3, appears in the right list three times; the similarity score again increases by 9.
So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9).
Once again consider your left and right lists. What is their similarity score? | 18934359 | let fs = require('fs');
let puzzleInput = fs.readFileSync('input.txt').toString().split("\n");
let firstLocations = [];
let secondLocations = [];
puzzleInput.forEach((line) => {
let parseLine = line.split(' ');
if (parseLine[0] != '') firstLocations.push(parseLine[0]);
if (parseLine[1] != '') secondLocations.push(parseLine[1]);
});
let similarityScore = 0;
firstLocations.forEach((firstLocation) => {
let occurancesInSecond = secondLocations.filter((secondLocation) => secondLocation === firstLocation).length;
let locationSimilarityScore = occurancesInSecond > 0 ? firstLocation * occurancesInSecond : 0;
similarityScore += locationSimilarityScore;
});
console.log(similarityScore); | javascript |
2024 | 3 | 1 | --- Day 3: Mull It Over ---
"Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.
The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"
The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up!
It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4.
However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing.
For example, consider the following section of corrupted memory:
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5).
Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? | 170807108 | const fs = require('fs');
const input = fs.readFileSync('input.txt', 'utf8');
const pattern = /mul\((\d+),(\d+)\)/g;
let sum = 0;
let match;
while ((match = pattern.exec(input)) !== null) {
sum += match[1] * match[2];
}
console.log(sum); | javascript |
2024 | 3 | 1 | --- Day 3: Mull It Over ---
"Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.
The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"
The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up!
It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4.
However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing.
For example, consider the following section of corrupted memory:
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5).
Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? | 170807108 | // PART 1
const fs = require('fs');
const path = require('path');
// Resolve the file path
const filePath = path.join(__dirname, 'input.txt');
const filePathTest1 = path.join(__dirname, 'test-1.txt');
const filePathTest2 = path.join(__dirname, 'test-2.txt');
// Read the file
function readFile(filePath) {
try {
const data = fs.readFileSync(filePath, 'utf8');
return data;
} catch (err) {
console.error('Error reading the file:', err);
return null;
}
}
const string = readFile(filePath);
const stringTest1 = readFile(filePathTest1);
const stringTest2 = readFile(filePathTest2);
// Match any group of 1-3 digits, separated by a comma, between "mul(" and ")"
const regex = /(?<=mul\()(\d{1,3},\d{1,3})(?=\))/g;
const arrayOfMatches = (string.match(regex)).map((el) => el.split(',').map(Number));
const arrayMultiplied = arrayOfMatches.map((el => el.reduce((a , b) => a * b)));
const arraySummed = arrayMultiplied.reduce((a, b) => a + b);
console.log(arraySummed);
// PART 2
// Regex to find string between "don't()" and "do()"
const regexPart2 = /don't\(\).*?do\(\)/g;
// Create first array of matches
let arrayofMarchesPart2 = string.split(regexPart2).filter(Boolean);
// Regex to find "don't()" without a following "do()"
const regexRemoveAfterLastDont = /don't\(\)(?!.*do\(\)).*/;
// Remove for each array element anything after the last "don't()" if no "do()" exists
arrayofMarchesPart2 = arrayofMarchesPart2.map(element => {
if (regexRemoveAfterLastDont.test(element)) {
return element.replace(regexRemoveAfterLastDont, '');
}
return element; // Return the element unchanged if the condition is not met
});
const arrayofMarchesPart2Bis = (arrayofMarchesPart2.map((el => (el.match(regex)).map((el) => el.split(',').map(Number))))).flat(1);
const arrayMultipliedPart2 = arrayofMarchesPart2Bis.map((el => el.reduce((a , b) => a * b)));
const arraySummedPart2 = arrayMultipliedPart2.reduce((a, b) => a + b);
console.log(arraySummedPart2); | javascript |
2024 | 3 | 1 | --- Day 3: Mull It Over ---
"Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.
The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"
The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up!
It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4.
However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing.
For example, consider the following section of corrupted memory:
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5).
Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? | 170807108 | let fs = require('fs');
let puzzleInput = fs.readFileSync('input.txt').toString();
let mul = (a, b) => a * b;
let regexp = /mul\([0-9]{1,3},[0-9]{1,3}\)/g;
let multiplications = puzzleInput.match(regexp);
let total = 0;
multiplications.forEach((thisMul) => {
let mulValue = eval(thisMul);
total += mulValue;
})
console.log(total); | javascript |
2024 | 3 | 1 | --- Day 3: Mull It Over ---
"Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.
The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"
The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up!
It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4.
However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing.
For example, consider the following section of corrupted memory:
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5).
Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? | 170807108 | const fs = require("fs");
let buffer, input, rows;
try {
buffer = fs.readFileSync(__dirname + "/input.txt", "utf8");
} catch (e) {
throw e;
}
input = buffer.toString();
rows = input.split("\n");
const multiply_sum = rows.reduce((accumulator, row) => {
if (row === "") return accumulator; // Empty row check, skip
let sum = 0;
let results;
// Match mul(x,y) from row as string
const regex = /mul\((\d+)\,(\d+)\)/g;
while ((results = regex.exec(row)) !== null) {
// Match numbers from mul(x,y)
sum += Number(results[1]) * Number(results[2]);
// console.log(`Found ${results[1]} x ${results[2]} at ${results.index}.`);
}
return accumulator + sum;
}, 0);
console.log({ multiply_sum }); | javascript |
2024 | 3 | 1 | --- Day 3: Mull It Over ---
"Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.
The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"
The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up!
It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4.
However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing.
For example, consider the following section of corrupted memory:
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5).
Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? | 170807108 | const fs = require('fs');
// Read the input file
const data = fs.readFileSync('input.txt', 'utf8');
const lines = data.trim().split('\n');
let totalSum = 0;
//Constructs regex to match criteria:
//mul(number1, number2) where number1 and number2 are 1-3 digit numbers
const regex = /mul\((\d{1,3}),(\d{1,3})\)/g;
lines.forEach(line => {
let match;
//regex.exec finds all the matches
while ((match = regex.exec(line)) !== null) {
//Parses the string to return an integer as a base10 (standard numeric output)
const number1 = parseInt(match[1], 10);
const number2 = parseInt(match[2], 10);
totalSum += number1 * number2;
}
});
console.log(`Total sum of all multiplied numbers: ${totalSum}`); | javascript |
2024 | 3 | 2 | --- Day 3: Mull It Over ---
"Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.
The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"
The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up!
It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4.
However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing.
For example, consider the following section of corrupted memory:
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5).
Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?
Your puzzle answer was 170807108.
--- Part Two ---
As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result.
There are two new instructions you'll need to handle:
The do() instruction enables future mul instructions.
The don't() instruction disables future mul instructions.
Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled.
For example:
xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))
This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction.
This time, the sum of the results is 48 (2*4 + 8*5).
Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications? | 74838033 | let fs = require('fs');
let puzzleInput = fs.readFileSync('input.txt').toString();
let mul = (a, b) => a * b;
let regEx = /do\(\)|don\'t\(\)|mul\([0-9]{1,3},[0-9]{1,3}\)/g;
let parts = puzzleInput.match(regEx);
let doing = true;
let total = 0;
parts.forEach((part) => {
if (doing && part.substring(0, 3) == 'mul') {
let value = eval(part);
total += value;
}
if (part.substring(0, 3) == 'do(') doing = true;
if (part.substring(0, 3) == 'don') doing = false;
});
console.log(total); | javascript |
2024 | 3 | 2 | --- Day 3: Mull It Over ---
"Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.
The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"
The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up!
It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4.
However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing.
For example, consider the following section of corrupted memory:
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5).
Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?
Your puzzle answer was 170807108.
--- Part Two ---
As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result.
There are two new instructions you'll need to handle:
The do() instruction enables future mul instructions.
The don't() instruction disables future mul instructions.
Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled.
For example:
xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))
This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction.
This time, the sum of the results is 48 (2*4 + 8*5).
Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications? | 74838033 | const fs = require('fs');
// Read the input file
const data = fs.readFileSync('input.txt', 'utf8');
const inputString = data.trim();
let totalSum = 0;
let mulEnabled = true;
const instructionRegex = /(do\(\))|(don't\(\))|mul\((\d{1,3}),(\d{1,3})\)/g;
let match;
while ((match = instructionRegex.exec(inputString)) !== null) {
if (match[1]) {
// Matched 'do()'
mulEnabled = true;
} else if (match[2]) {
// Matched "don't()"
mulEnabled = false;
} else if (match[3] && mulEnabled) {
// Matched 'mul(X,Y)' and mul is enabled
const number1 = parseInt(match[3], 10);
const number2 = parseInt(match[4], 10);
totalSum += number1 * number2;
}
}
console.log(`Total sum of all multiplied numbers: ${totalSum}`); | javascript |
2024 | 3 | 2 | --- Day 3: Mull It Over ---
"Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.
The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"
The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up!
It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4.
However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing.
For example, consider the following section of corrupted memory:
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5).
Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?
Your puzzle answer was 170807108.
--- Part Two ---
As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result.
There are two new instructions you'll need to handle:
The do() instruction enables future mul instructions.
The don't() instruction disables future mul instructions.
Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled.
For example:
xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))
This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction.
This time, the sum of the results is 48 (2*4 + 8*5).
Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications? | 74838033 | const fs = require("fs");
const path = require("path");
const fileTxt = fs.readFileSync(path.join(__dirname, "input.txt"));
const inputFromAdvent = fileTxt.toString();
const parseInput = (input) => {
// want to take only between () and comma inside after mul. Eg mul(2,4) 2,4
const regex = /mul\((\d+),(\d+)\)/g;
const matches = input.match(regex);
return matches.map((match) => match.slice(4, -1).split(",").map(Number));
};
const parseAndMultiplyInput = (input) => {
return input
.split("do()") // split into chunks
.map((chunk) => chunk.split("don't()")[0]) // remove don't()
.map((s) => [...s.matchAll(/mul\((\d+),(\d+)\)/g)]) // find all mul pairs
.flatMap((m) => m.map((m) => m[1] * m[2])) // multiply pairs
.reduce((acc, curr) => acc + curr, 0); // sum up
};
const multiplyPairsTotal = (pairs) => {
return pairs.reduce((acc, pair) => acc + pair[0] * pair[1], 0);
};
const main1 = () => {
console.log(multiplyPairsTotal(parseInput(inputFromAdvent)));
};
const main2 = () => {
console.log(parseAndMultiplyInput(inputFromAdvent));
};
module.exports = { parseInput, multiplyPairsTotal, parseAndMultiplyInput };
// main1();
main2(); | javascript |
2024 | 3 | 2 | --- Day 3: Mull It Over ---
"Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.
The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"
The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up!
It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4.
However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing.
For example, consider the following section of corrupted memory:
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5).
Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?
Your puzzle answer was 170807108.
--- Part Two ---
As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result.
There are two new instructions you'll need to handle:
The do() instruction enables future mul instructions.
The don't() instruction disables future mul instructions.
Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled.
For example:
xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))
This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction.
This time, the sum of the results is 48 (2*4 + 8*5).
Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications? | 74838033 | const fs = require('fs');
function question2() {
fs.readFile('./input.txt', (err, data) => {
const memory = data.toString().replace(/\r/g, '').trimEnd();
const regex = /mul\(\d+,\d+\)|do\(\)|don't\(\)/g;
const matches = memory.matchAll(regex);
const instructions = [];
for (const match of matches) {
if (match[0].includes('mul')) {
instructions.push(match[0].slice(4, -1).split(','));
} else {
instructions.push(match[0]);
}
}
let addEnabled = true;
const result = instructions.reduce((acc, instr) => {
if (typeof instr !== 'string' && addEnabled) {
return (acc += instr[0] * instr[1]);
} else if (instr === 'do()') {
addEnabled = true;
return acc;
} else if (instr === "don't()") {
addEnabled = false;
return acc;
} else {
return acc;
}
}, 0);
console.log(result);
});
}
question2(); | javascript |
2024 | 3 | 2 | --- Day 3: Mull It Over ---
"Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.
The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"
The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up!
It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4.
However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing.
For example, consider the following section of corrupted memory:
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5).
Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?
Your puzzle answer was 170807108.
--- Part Two ---
As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result.
There are two new instructions you'll need to handle:
The do() instruction enables future mul instructions.
The don't() instruction disables future mul instructions.
Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled.
For example:
xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))
This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction.
This time, the sum of the results is 48 (2*4 + 8*5).
Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications? | 74838033 | const fs = require('fs');
// Function to read and process the input data
function readInput(filePath) {
try {
const data = fs.readFileSync(filePath, 'utf8');
return data.trim(); // Return the input string after trimming any extra whitespace
} catch (error) {
console.error('Error reading the file:', error);
return '';
}
}
// Function to process the instructions and compute the sum of valid multiplications
function calculateTotalSum(inputString) {
let totalSum = 0;
let mulEnabled = true;
const instructionRegex = /(do\(\))|(don't\(\))|mul\((\d{1,3}),(\d{1,3})\)/g;
let match;
// Iterate through each instruction in the input string
while ((match = instructionRegex.exec(inputString)) !== null) {
if (match[1]) {
mulEnabled = true; // Enable mul if 'do()' is matched
} else if (match[2]) {
mulEnabled = false; // Disable mul if "don't()" is matched
} else if (match[3] && mulEnabled) {
// If a valid 'mul(X,Y)' is matched and mul is enabled, multiply and add to the total sum
const number1 = parseInt(match[3], 10);
const number2 = parseInt(match[4], 10);
totalSum += number1 * number2;
}
}
return totalSum;
}
// Main function to execute the program
function main() {
const inputString = readInput('input.txt');
if (inputString) {
const totalSum = calculateTotalSum(inputString);
console.log(`Total sum of all multiplied numbers: ${totalSum}`);
}
}
main(); // Run the main function to start the process | javascript |
2024 | 4 | 1 | --- Day 4: Ceres Search ---
"Looks like the Chief's not here. Next!" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station!
As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS.
This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .:
..X...
.SAMX.
.A..A.
XMAS.S
.X....
The actual word search will be full of letters instead. For example:
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .:
....XXMAS.
.SAMXMS...
...S..A...
..A.A.MS.X
XMASAMX.MM
X.....XA.A
S.S.S.S.SS
.A.A.A.A.A
..M.M.M.MM
.X.X.XMASX
Take a look at the little Elf's word search. How many times does XMAS appear? | 2434 | import fs from "node:fs";
const a = fs.readFileSync("./input.txt", "utf8").toString().split("\n");
const data = a.map((item) => item.split(""));
const values = {
horizontalLR: 0,
horizontalRL: 0,
verticalTB: 0,
verticalBT: 0,
diagonalTLtoBR: 0,
diagonalBRtoTL: 0,
diagonalTRtoBL: 0,
diagonalBLtoTR: 0,
};
data.forEach((item, itemIdx) => {
item.forEach((child, childIdx) => {
// Horizontal (left to right)
if (child === "X") {
if (data[itemIdx][childIdx + 1] === "M") {
if (data[itemIdx][childIdx + 2] === "A") {
if (data[itemIdx][childIdx + 3] === "S") values.horizontalLR += 1;
}
}
// Descending Diagonal (center to bottom right)
if (data[itemIdx + 1][childIdx + 1] === "M") {
if (data[itemIdx + 2][childIdx + 2] === "A") {
if (data[itemIdx + 3][childIdx + 3] === "S")
values.diagonalTLtoBR += 1;
}
}
// Descending Vertical (center to bottom)
if (data[itemIdx + 1][childIdx] === "M") {
if (data[itemIdx + 2][childIdx] === "A") {
if (data[itemIdx + 3][childIdx] === "S") values.verticalTB += 1;
}
}
// Descending diagonal (center to bottom left)
if (childIdx >= 3) {
if (data[itemIdx + 1][childIdx - 1] === "M") {
if (data[itemIdx + 2][childIdx - 2] === "A") {
if (data[itemIdx + 3][childIdx - 3] === "S")
values.diagonalTRtoBL += 1;
}
}
}
// Horizontal (right to left)
if (childIdx >= 3) {
if (data[itemIdx][childIdx - 1] === "M") {
if (data[itemIdx][childIdx - 2] === "A") {
if (data[itemIdx][childIdx - 3] === "S") values.horizontalRL += 1;
}
}
}
// ascending diagonal (center to top left)
if (itemIdx >= 3 && childIdx >= 3) {
if (data[itemIdx - 1][childIdx - 1] === "M") {
if (data[itemIdx - 2][childIdx - 2] === "A") {
if (data[itemIdx - 3][childIdx - 3] === "S")
values.diagonalBRtoTL += 1;
}
}
}
// ascending vertical (center to top)
if (itemIdx >= 3) {
if (data[itemIdx - 1][childIdx] === "M") {
if (data[itemIdx - 2][childIdx] === "A") {
if (data[itemIdx - 3][childIdx] === "S") values.verticalBT += 1;
}
}
}
// ascending diagonal (center to top right)
if (itemIdx >= 3) {
if (data[itemIdx - 1][childIdx + 1] === "M") {
if (data[itemIdx - 2][childIdx + 2] === "A") {
if (data[itemIdx - 3][childIdx + 3] === "S")
values.diagonalBLtoTR += 1;
}
}
}
}
});
});
console.log(values);
let count = 0;
Object.values(values).forEach((item) => {
count += item;
});
console.log(count); | javascript |
2024 | 4 | 1 | --- Day 4: Ceres Search ---
"Looks like the Chief's not here. Next!" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station!
As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS.
This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .:
..X...
.SAMX.
.A..A.
XMAS.S
.X....
The actual word search will be full of letters instead. For example:
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .:
....XXMAS.
.SAMXMS...
...S..A...
..A.A.MS.X
XMASAMX.MM
X.....XA.A
S.S.S.S.SS
.A.A.A.A.A
..M.M.M.MM
.X.X.XMASX
Take a look at the little Elf's word search. How many times does XMAS appear? | 2434 | const fs = require("fs");
// const puzzleInput = fs.readFileSync("./sample_input.txt").toString().split('\n');
const puzzleInput = fs.readFileSync("./input.txt").toString().split('\n');
function findWordCount(grid, word) {
const rows = grid.length;
const cols = grid[0].length;
const wordLength = word.length;
const reverseWord = word.split('').reverse().join('');
let count = 0;
function checkHorizontal(row, col) {
if (col <= cols - wordLength) {
const horizontalWord = grid[row].slice(col, col + wordLength);
if (horizontalWord === word || horizontalWord === reverseWord) {
count++;
// console.log(`Found ${word} horizontally at row ${row}, starting column ${col}`);
}
}
}
function checkVertical(row, col) {
if (row <= rows - wordLength) {
let verticalWord = '';
for (let i = 0; i < wordLength; i++) {
verticalWord += grid[row + i][col];
}
if (verticalWord === word || verticalWord === reverseWord) {
count++;
// console.log(`Found ${word} vertically at column ${col}, starting row ${row}`);
}
}
}
function checkDiagonal(row, col) {
// Diagonal down-right
if (row <= rows - wordLength && col <= cols - wordLength) {
let diagonalWord = '';
for (let i = 0; i < wordLength; i++) {
diagonalWord += grid[row + i][col + i];
}
if (diagonalWord === word || diagonalWord === reverseWord) {
count++;
// console.log(`Found ${word} diagonally (down-right) starting at row ${row}, column ${col}`);
}
}
// Diagonal down-left
if (row <= rows - wordLength && col >= wordLength - 1) {
let diagonalWord = '';
for (let i = 0; i < wordLength; i++) {
diagonalWord += grid[row + i][col - i];
}
if (diagonalWord === word || diagonalWord === reverseWord) {
count++;
// console.log(`Found ${word} diagonally (down-left) starting at row ${row}, column ${col}`);
}
}
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
checkHorizontal(r, c);
checkVertical(r, c);
checkDiagonal(r, c);
}
}
return count;
}
const wordCount = findWordCount(puzzleInput, "XMAS");
console.log(`Part 1: ${wordCount}`); | javascript |
2024 | 4 | 1 | --- Day 4: Ceres Search ---
"Looks like the Chief's not here. Next!" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station!
As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS.
This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .:
..X...
.SAMX.
.A..A.
XMAS.S
.X....
The actual word search will be full of letters instead. For example:
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .:
....XXMAS.
.SAMXMS...
...S..A...
..A.A.MS.X
XMASAMX.MM
X.....XA.A
S.S.S.S.SS
.A.A.A.A.A
..M.M.M.MM
.X.X.XMASX
Take a look at the little Elf's word search. How many times does XMAS appear? | 2434 | const fs = require('fs');
// Read the input file
const data = fs.readFileSync('input.txt', 'utf8');
const lines = data.trim().split('\n');
const grid = lines.map(line => line.trim().split(''));
const numRows = grid.length;
const numCols = grid[0].length;
const word = 'XMAS';
let count = 0;
// Directions: N, NE, E, SE, S, SW, W, NW
const directions = [
[-1, 0], // N
[-1, 1], // NE
[ 0, 1], // E
[ 1, 1], // SE
[ 1, 0], // S
[ 1, -1], // SW
[ 0, -1], // W
[-1, -1] // NW
];
for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
for (let [dx, dy] of directions) {
let match = true;
for (let k = 0; k < word.length; k++) {
const x = row + k * dx;
const y = col + k * dy;
if (x < 0 || x >= numRows || y < 0 || y >= numCols || grid[x][y] !== word[k]) {
match = false;
break;
}
}
if (match) {
count++;
}
}
}
}
console.log(`The word "XMAS" appears ${count} times in the grid.`); | javascript |
2024 | 4 | 1 | --- Day 4: Ceres Search ---
"Looks like the Chief's not here. Next!" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station!
As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS.
This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .:
..X...
.SAMX.
.A..A.
XMAS.S
.X....
The actual word search will be full of letters instead. For example:
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .:
....XXMAS.
.SAMXMS...
...S..A...
..A.A.MS.X
XMASAMX.MM
X.....XA.A
S.S.S.S.SS
.A.A.A.A.A
..M.M.M.MM
.X.X.XMASX
Take a look at the little Elf's word search. How many times does XMAS appear? | 2434 | import fs from "fs";
const countXmasOccurrences = (inputFilePath) => {
const xmasMatrix = [];
try {
const text = fs.readFileSync(inputFilePath, "utf8");
if (!text) return 0;
const rows = text.trim().split("\n");
for (const row of rows) {
xmasMatrix.push(row.split(""));
}
let xmasCounter = 0;
for (let i = 0; i < xmasMatrix.length; i++) {
for (let j = 0; j < xmasMatrix[i].length; j++) {
const currentChar = xmasMatrix[i][j];
if (xmasMatrix?.[i - 3]?.[j - 3]) {
const topLeftDiagonal =
currentChar +
xmasMatrix[i - 1][j - 1] +
xmasMatrix[i - 2][j - 2] +
xmasMatrix[i - 3][j - 3];
if (topLeftDiagonal === "XMAS") xmasCounter++;
}
if (xmasMatrix?.[i - 3]?.[j + 3]) {
const topRightDiagonal =
currentChar +
xmasMatrix[i - 1][j + 1] +
xmasMatrix[i - 2][j + 2] +
xmasMatrix[i - 3][j + 3];
if (topRightDiagonal === "XMAS") xmasCounter++;
}
if (xmasMatrix?.[i + 3]?.[j - 3]) {
const botLeftDiagonal =
currentChar +
xmasMatrix[i + 1][j - 1] +
xmasMatrix[i + 2][j - 2] +
xmasMatrix[i + 3][j - 3];
if (botLeftDiagonal === "XMAS") xmasCounter++;
}
if (xmasMatrix?.[i + 3]?.[j + 3]) {
const botRightDiagonal =
currentChar +
xmasMatrix[i + 1][j + 1] +
xmasMatrix[i + 2][j + 2] +
xmasMatrix[i + 3][j + 3];
if (botRightDiagonal === "XMAS") xmasCounter++;
}
if (xmasMatrix[i]?.[j - 3]) {
const left =
currentChar +
xmasMatrix[i][j - 1] +
xmasMatrix[i][j - 2] +
xmasMatrix[i][j - 3];
if (left === "XMAS") xmasCounter++;
}
if (xmasMatrix[i]?.[j + 3]) {
const right =
currentChar +
xmasMatrix[i][j + 1] +
xmasMatrix[i][j + 2] +
xmasMatrix[i][j + 3];
if (right === "XMAS") xmasCounter++;
}
if (xmasMatrix?.[i - 3]?.[j]) {
const top =
currentChar +
xmasMatrix[i - 1][j] +
xmasMatrix[i - 2][j] +
xmasMatrix[i - 3][j];
if (top === "XMAS") xmasCounter++;
}
if (xmasMatrix?.[i + 3]?.[j]) {
const bot =
currentChar +
xmasMatrix[i + 1][j] +
xmasMatrix[i + 2][j] +
xmasMatrix[i + 3][j];
if (bot === "XMAS") xmasCounter++;
}
}
}
return xmasCounter;
} catch (err) {
console.error(err);
}
};
const totalXmasOccurrences = countXmasOccurrences("./puzzle-input.txt");
console.log(totalXmasOccurrences); | javascript |
2024 | 4 | 1 | --- Day 4: Ceres Search ---
"Looks like the Chief's not here. Next!" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station!
As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS.
This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .:
..X...
.SAMX.
.A..A.
XMAS.S
.X....
The actual word search will be full of letters instead. For example:
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .:
....XXMAS.
.SAMXMS...
...S..A...
..A.A.MS.X
XMASAMX.MM
X.....XA.A
S.S.S.S.SS
.A.A.A.A.A
..M.M.M.MM
.X.X.XMASX
Take a look at the little Elf's word search. How many times does XMAS appear? | 2434 | let fs = require('fs');
let rows = fs.readFileSync('input.txt').toString().split("\n");
// We need a Width and a Height - we will assume it is a rectangular wordsearch and that all rows are the same length
const WIDTH = rows[0].length;
const HEIGHT = rows.length;
const DIRECTIONS = [
[1, 0], // East
[1, 1], // South East
[0, 1], // South
[-1, 1], // South West
[-1, 0], // West
[-1, -1], // North West
[0, -1], // North
[1, -1], // North East
];
const SEARCH = 'XMAS';
// Keep a running total of how many times we have found the Search Word
let runningTotal = 0;
rows.forEach((row, rowIndex) => {
if (row.length > 0) {
[...row].forEach((letter, colIndex) => {
if (letter === SEARCH[0]) {
DIRECTIONS.forEach((direction) => {
for (let i = 1; i <= SEARCH.length - 1; i++) {
let coordY = rowIndex + (direction[0] * i);
let coordX = colIndex + (direction[1] * i);
if (coordY < HEIGHT && coordY >= 0 && coordX < WIDTH && coordX >= 0) {
if (rows[coordY][coordX] === SEARCH[i]) {
if (i === SEARCH.length - 1) {
runningTotal++;
break;
}
} else {
break;
}
}
}
});
}
});
}
});
console.log(runningTotal); | javascript |
2024 | 4 | 2 | --- Day 4: Ceres Search ---
"Looks like the Chief's not here. Next!" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station!
As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS.
This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .:
..X...
.SAMX.
.A..A.
XMAS.S
.X....
The actual word search will be full of letters instead. For example:
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .:
....XXMAS.
.SAMXMS...
...S..A...
..A.A.MS.X
XMASAMX.MM
X.....XA.A
S.S.S.S.SS
.A.A.A.A.A
..M.M.M.MM
.X.X.XMASX
Take a look at the little Elf's word search. How many times does XMAS appear?
Your puzzle answer was 2434.
--- Part Two ---
The Elf looks quizzically at you. Did you misunderstand the assignment?
Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this:
M.S
.A.
M.S
Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards.
Here's the same example from before, but this time all of the X-MASes have been kept instead:
.M.S......
..A..MSMS.
.M.S.MAA..
..A.ASMSM.
.M.S.M....
..........
S.S.S.S.S.
.A.A.A.A..
M.M.M.M.M.
..........
In this example, an X-MAS appears 9 times.
Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear? | 1835 | import fs from "node:fs";
const a = fs.readFileSync("./input.txt", "utf8").toString().split("\n");
const data = a.map((item) => item.split(""));
let count = 0;
data.forEach((_, vertIdx) => {
data[vertIdx].forEach((_, horzIdx) => {
if (vertIdx >= 1 && horzIdx >= 1) {
if (data[vertIdx][horzIdx] === "A") {
if (
data[vertIdx - 1][horzIdx - 1] === "M" &&
data[vertIdx - 1][horzIdx + 1] === "S" &&
data[vertIdx + 1][horzIdx - 1] === "M" &&
data[vertIdx + 1][horzIdx + 1] === "S"
) {
count += 1;
}
if (
data[vertIdx - 1][horzIdx - 1] === "S" &&
data[vertIdx - 1][horzIdx + 1] === "S" &&
data[vertIdx + 1][horzIdx - 1] === "M" &&
data[vertIdx + 1][horzIdx + 1] === "M"
) {
count += 1;
}
if (
data[vertIdx - 1][horzIdx - 1] === "M" &&
data[vertIdx - 1][horzIdx + 1] === "M" &&
data[vertIdx + 1][horzIdx - 1] === "S" &&
data[vertIdx + 1][horzIdx + 1] === "S"
) {
count += 1;
}
if (
data[vertIdx - 1][horzIdx - 1] === "S" &&
data[vertIdx - 1][horzIdx + 1] === "M" &&
data[vertIdx + 1][horzIdx - 1] === "S" &&
data[vertIdx + 1][horzIdx + 1] === "M"
) {
count += 1;
}
}
}
});
});
console.log(count); | javascript |
2024 | 4 | 2 | --- Day 4: Ceres Search ---
"Looks like the Chief's not here. Next!" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station!
As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS.
This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .:
..X...
.SAMX.
.A..A.
XMAS.S
.X....
The actual word search will be full of letters instead. For example:
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .:
....XXMAS.
.SAMXMS...
...S..A...
..A.A.MS.X
XMASAMX.MM
X.....XA.A
S.S.S.S.SS
.A.A.A.A.A
..M.M.M.MM
.X.X.XMASX
Take a look at the little Elf's word search. How many times does XMAS appear?
Your puzzle answer was 2434.
--- Part Two ---
The Elf looks quizzically at you. Did you misunderstand the assignment?
Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this:
M.S
.A.
M.S
Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards.
Here's the same example from before, but this time all of the X-MASes have been kept instead:
.M.S......
..A..MSMS.
.M.S.MAA..
..A.ASMSM.
.M.S.M....
..........
S.S.S.S.S.
.A.A.A.A..
M.M.M.M.M.
..........
In this example, an X-MAS appears 9 times.
Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear? | 1835 | const fs = require("fs");
const filename = "input.txt";
var buffer, input, rows;
try {
buffer = fs.readFileSync(__dirname + "/" + filename, "utf8");
} catch (e) {
throw e;
}
input = buffer.toString();
rows = input.split("\n").map(el => el.split(""));
function find_xmas(letter, i, j) {
let total = 0;
if (letter !== 'A') return total; // This aint it fam
// If the coords exists, check for the letter
// M ? S
// ? A ?
// M ? S
if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === "M") {
if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === "S") {
if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === "M") {
if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === "S") {
total++;
}
}
}
}
// M ? M
// ? A ?
// S ? S
if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === "M") {
if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === "M") {
if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === "S") {
if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === "S") {
total++;
}
}
}
}
// S ? S
// ? A ?
// M ? M
if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === "S") {
if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === "S") {
if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === "M") {
if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === "M") {
total++;
}
}
}
}
// S ? M
// ? A ?
// S ? M
if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === "S") {
if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === "M") {
if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === "S") {
if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === "M") {
total++;
}
}
}
}
return total;
}
let found_xmass = 0;
for (let i = 0; i < rows.length; i++) {
for (let j = 0; j < rows[i].length; j++) {
found_xmass += find_xmas(rows[i][j], i, j);
}
}
console.log({ found_xmass }); | javascript |
2024 | 4 | 2 | --- Day 4: Ceres Search ---
"Looks like the Chief's not here. Next!" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station!
As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS.
This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .:
..X...
.SAMX.
.A..A.
XMAS.S
.X....
The actual word search will be full of letters instead. For example:
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .:
....XXMAS.
.SAMXMS...
...S..A...
..A.A.MS.X
XMASAMX.MM
X.....XA.A
S.S.S.S.SS
.A.A.A.A.A
..M.M.M.MM
.X.X.XMASX
Take a look at the little Elf's word search. How many times does XMAS appear?
Your puzzle answer was 2434.
--- Part Two ---
The Elf looks quizzically at you. Did you misunderstand the assignment?
Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this:
M.S
.A.
M.S
Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards.
Here's the same example from before, but this time all of the X-MASes have been kept instead:
.M.S......
..A..MSMS.
.M.S.MAA..
..A.ASMSM.
.M.S.M....
..........
S.S.S.S.S.
.A.A.A.A..
M.M.M.M.M.
..........
In this example, an X-MAS appears 9 times.
Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear? | 1835 | const fs = require('fs');
// Function to read the input file and split it into rows
function readInput(filePath) {
try {
const data = fs.readFileSync(filePath, 'utf-8');
return data.split("\n").filter(row => row.length > 0); // Filter out any empty rows
} catch (error) {
console.error('Error reading the file:', error);
return [];
}
}
// Function to check if an "X-MAS" pattern is found at a given position in the grid
function isXMASPattern(rows, rowIndex, colIndex, WIDTH, HEIGHT) {
// Check if we're within bounds and the letter at the center is 'A'
if (rowIndex > 0 && rowIndex < HEIGHT - 1 && colIndex > 0 && colIndex < WIDTH - 1 && rows[rowIndex][colIndex] === 'A') {
return (
// Check for diagonals forming 'X-MAS' in both directions
(
rows[rowIndex + 1][colIndex + 1] === 'M' && rows[rowIndex - 1][colIndex - 1] === 'S' ||
rows[rowIndex + 1][colIndex + 1] === 'S' && rows[rowIndex - 1][colIndex - 1] === 'M'
) &&
(
rows[rowIndex + 1][colIndex - 1] === 'M' && rows[rowIndex - 1][colIndex + 1] === 'S' ||
rows[rowIndex + 1][colIndex - 1] === 'S' && rows[rowIndex - 1][colIndex + 1] === 'M'
)
);
}
return false;
}
// Function to count occurrences of the "X-MAS" pattern in the grid
function countXMASPatterns(rows, WIDTH, HEIGHT) {
let runningTotal = 0;
// Loop over each row and column to check for "X-MAS" patterns
rows.forEach((row, rowIndex) => {
[...row].forEach((letter, colIndex) => {
if (isXMASPattern(rows, rowIndex, colIndex, WIDTH, HEIGHT)) {
runningTotal++;
}
});
});
return runningTotal;
}
// Main function to orchestrate the entire process
function main() {
const rows = readInput('input.txt');
if (rows.length === 0) return;
const WIDTH = rows[0].length;
const HEIGHT = rows.length;
// Count the occurrences of "X-MAS" patterns
const totalPatterns = countXMASPatterns(rows, WIDTH, HEIGHT);
// Output the result
console.log(totalPatterns);
}
main(); // Run the main function | javascript |
2024 | 4 | 2 | --- Day 4: Ceres Search ---
"Looks like the Chief's not here. Next!" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station!
As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS.
This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .:
..X...
.SAMX.
.A..A.
XMAS.S
.X....
The actual word search will be full of letters instead. For example:
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .:
....XXMAS.
.SAMXMS...
...S..A...
..A.A.MS.X
XMASAMX.MM
X.....XA.A
S.S.S.S.SS
.A.A.A.A.A
..M.M.M.MM
.X.X.XMASX
Take a look at the little Elf's word search. How many times does XMAS appear?
Your puzzle answer was 2434.
--- Part Two ---
The Elf looks quizzically at you. Did you misunderstand the assignment?
Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this:
M.S
.A.
M.S
Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards.
Here's the same example from before, but this time all of the X-MASes have been kept instead:
.M.S......
..A..MSMS.
.M.S.MAA..
..A.ASMSM.
.M.S.M....
..........
S.S.S.S.S.
.A.A.A.A..
M.M.M.M.M.
..........
In this example, an X-MAS appears 9 times.
Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear? | 1835 | let fs = require('fs');
let rows = fs.readFileSync('input.txt').toString().split("\n");
// We need a Width and a Height - we will assume it is a rectangular wordsearch and that all rows are the same length
const WIDTH = rows[0].length;
const HEIGHT = rows.length;
// Keep a running total of how many times we have found the Search Word
let runningTotal = 0;
rows.forEach((row, rowIndex) => {
if (row.length > 0) {
[...row].forEach((letter, colIndex) => {
if (letter === 'A') {
if (
rowIndex > 0 && rowIndex < HEIGHT - 1 &&
colIndex > 0 && colIndex < WIDTH - 1 &&
(
(rows[rowIndex + 1][colIndex + 1] === 'M' && rows[rowIndex - 1][colIndex - 1] === 'S') ||
(rows[rowIndex + 1][colIndex + 1] === 'S' && rows[rowIndex - 1][colIndex - 1] === 'M')
) &&
(
(rows[rowIndex + 1][colIndex - 1] === 'M' && rows[rowIndex - 1][colIndex + 1] === 'S') ||
(rows[rowIndex + 1][colIndex - 1] === 'S' && rows[rowIndex - 1][colIndex + 1] === 'M')
)
) {
runningTotal++;
}
}
});
}
});
console.log(runningTotal); | javascript |
2024 | 4 | 2 | --- Day 4: Ceres Search ---
"Looks like the Chief's not here. Next!" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station!
As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS.
This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .:
..X...
.SAMX.
.A..A.
XMAS.S
.X....
The actual word search will be full of letters instead. For example:
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .:
....XXMAS.
.SAMXMS...
...S..A...
..A.A.MS.X
XMASAMX.MM
X.....XA.A
S.S.S.S.SS
.A.A.A.A.A
..M.M.M.MM
.X.X.XMASX
Take a look at the little Elf's word search. How many times does XMAS appear?
Your puzzle answer was 2434.
--- Part Two ---
The Elf looks quizzically at you. Did you misunderstand the assignment?
Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this:
M.S
.A.
M.S
Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards.
Here's the same example from before, but this time all of the X-MASes have been kept instead:
.M.S......
..A..MSMS.
.M.S.MAA..
..A.ASMSM.
.M.S.M....
..........
S.S.S.S.S.
.A.A.A.A..
M.M.M.M.M.
..........
In this example, an X-MAS appears 9 times.
Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear? | 1835 | const fs = require('fs');
// Read the input file and create the grid
const data = fs.readFileSync('input.txt', 'utf8');
const lines = data.trim().split('\n');
const grid = lines.map(line => line.trim().split(''));
const numRows = grid.length;
const numCols = grid[0].length;
let count = 0;
// Directions for diagonals
const dir1 = [-1, -1]; // Top-left to bottom-right
const dir2 = [-1, 1]; // Top-right to bottom-left
for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
if (grid[row][col] === 'A') {
let valid1 = false;
let valid2 = false;
// Check diagonal from top-left to bottom-right
// Check diagonal from top-left to bottom-right
if (
row - 1 >= 0 && col - 1 >= 0 &&
row + 1 < numRows && col + 1 < numCols &&
(
(grid[row - 1][col - 1] === 'M' && grid[row + 1][col + 1] === 'S') ||
(grid[row - 1][col - 1] === 'S' && grid[row + 1][col + 1] === 'M')
)
) {
valid1 = true;
}
// Check diagonal from top-right to bottom-left
if (
row - 1 >= 0 && col + 1 < numCols &&
row + 1 < numRows && col - 1 >= 0 &&
(
(grid[row - 1][col + 1] === 'M' && grid[row + 1][col - 1] === 'S') ||
(grid[row - 1][col + 1] === 'S' && grid[row + 1][col - 1] === 'M')
)
) {
valid2 = true;
}
// If both diagonals form 'MAS' or 'SAM', increment count
if (valid1 && valid2) {
count++;
}
}
}
}
console.log(`Number of X-MAS patterns found: ${count}`); | javascript |
2024 | 6 | 1 | --- Day 6: Guard Gallivant ---
The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians.
You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab.
Maybe you can work out where the guard will go ahead of time so that The Historians can search safely?
You start by making a map (your puzzle input) of the situation. For example:
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #.
Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps:
If there is something directly in front of you, turn right 90 degrees.
Otherwise, take a step forward.
Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes):
....#.....
....^....#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction:
....#.....
........>#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward:
....#.....
.........#
..........
..#.......
.......#..
..........
.#......v.
........#.
#.........
......#...
This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent):
....#.....
.........#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#v..
By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X:
....#.....
....XXXXX#
....X...X.
..#.X...X.
..XXXXX#X.
..X.X.X.X.
.#XXXXXXX.
.XXXXXXX#.
#XXXXXXX..
......#X..
In this example, the guard will visit 41 distinct positions on your map.
Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? | 4890 | const fs = require('fs');
// Read the input file
const input = fs.readFileSync('input.txt', 'utf8').trim();
const map = input.split('\n');
// Directions: Up, Right, Down, Left
const directions = ['^', '>', 'v', '<'];
let direction = '';
let position = { x: 0, y: 0 };
// Parse the map to find the initial position and direction of the guard
for (let y = 0; y < map.length; y++) {
for (let x = 0; x < map[y].length; x++) {
if (directions.includes(map[y][x])) {
position = { x, y };
direction = map[y][x];
break;
}
}
if (direction) break;
}
// Directions mapping for movement
const movement = {
'^': { dx: 0, dy: -1 }, // Up
'>': { dx: 1, dy: 0 }, // Right
'v': { dx: 0, dy: 1 }, // Down
'<': { dx: -1, dy: 0 }, // Left
};
// Set to track the visited positions
const visited = new Set();
visited.add(`${position.x},${position.y}`);
// Function to turn right
const turnRight = (currentDirection) => {
const idx = directions.indexOf(currentDirection);
return directions[(idx + 1) % 4];
};
let guardRunning = true;
while (guardRunning) {
// Calculate the next position
const nextX = position.x + movement[direction].dx;
const nextY = position.y + movement[direction].dy;
// Check if the next position is outside the map
if (
nextX < 0 ||
nextX >= map[0].length ||
nextY < 0 ||
nextY >= map.length
) {
guardRunning = false; // Guard leaves the map
} else {
// Check if the next position is an obstacle
if (map[nextY][nextX] === '#') {
// Turn right
direction = turnRight(direction);
} else {
// Move forward
position.x = nextX;
position.y = nextY;
visited.add(`${position.x},${position.y}`);
}
}
}
console.log(visited.size); // The number of distinct positions visited | javascript |
2024 | 6 | 1 | --- Day 6: Guard Gallivant ---
The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians.
You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab.
Maybe you can work out where the guard will go ahead of time so that The Historians can search safely?
You start by making a map (your puzzle input) of the situation. For example:
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #.
Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps:
If there is something directly in front of you, turn right 90 degrees.
Otherwise, take a step forward.
Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes):
....#.....
....^....#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction:
....#.....
........>#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward:
....#.....
.........#
..........
..#.......
.......#..
..........
.#......v.
........#.
#.........
......#...
This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent):
....#.....
.........#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#v..
By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X:
....#.....
....XXXXX#
....X...X.
..#.X...X.
..XXXXX#X.
..X.X.X.X.
.#XXXXXXX.
.XXXXXXX#.
#XXXXXXX..
......#X..
In this example, the guard will visit 41 distinct positions on your map.
Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? | 4890 | const fs = require("fs");
const inputText = "./input.txt";
fs.readFile(inputText, "utf8", (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
const rows = data.split("\n").map(row => row.split(""));
let guardLocation = rows
.map((row, i) => {
if (row.includes("^")) {
// Turn guard icon into a normal traversable space
const guardLocation = row.indexOf("^")
rows[i][guardLocation] = ".";
return { x: i, y: guardLocation }
}
})
.filter(row => row)[0];
console.log(part1(rows, guardLocation));
console.log(part2(rows, guardLocation));
});
const directions = {
"up": { dx: -1, dy: 0, next: "right" },
"right": { dx: 0, dy: 1, next: "down" },
"down": { dx: 1, dy: 0, next: "left" },
"left": { dx: 0, dy: -1, next: "up" },
};
// Get all places guard visits
const getPlacesVisited = (rows, guardLocation) => {
let placesVisited = new Set();
let guardDirection = "up";
let nextGuardLocation;
while (nextGuardLocation !== null) {
const { x, y } = guardLocation;
const { dx, dy} = directions[guardDirection];
let possibleNextCoords = { x: x + dx, y: y + dy };
// Check if in bounds
if (possibleNextCoords.x < 0 || possibleNextCoords.x > rows.length - 1||
possibleNextCoords.y < 0 || possibleNextCoords.y > rows[0].length - 1) {
placesVisited.add(`${x}, ${y}`);
nextGuardLocation = null;
break;
}
if (rows[possibleNextCoords.x][possibleNextCoords.y] !== ".") {
guardDirection = directions[guardDirection].next;
} else {
guardLocation = possibleNextCoords;
nextGuardLocation = rows[possibleNextCoords.x][possibleNextCoords.y];
placesVisited.add(`${x}, ${y}`);
}
}
return placesVisited;
}
const checkInfiniteLoop = (rows, guardLocation) => {
const placesVisited = new Set();
let guardDirection = "up";
let nextGuardLocation;
while (true) {
const { x, y } = guardLocation;
const { dx, dy} = directions[guardDirection];
let possibleNextCoords = { x: x + dx, y: y + dy };
// Check if guard has been here before, and in the same direction, indicating an infinite loop
const currentPosition = `${x}, ${y}, ${guardDirection}`
if (placesVisited.has(currentPosition)) {
return true;
}
placesVisited.add(currentPosition);
// Check if in bounds
if (possibleNextCoords.x < 0 || possibleNextCoords.x > rows.length - 1||
possibleNextCoords.y < 0 || possibleNextCoords.y > rows[0].length - 1) {
return false;
}
if (rows[possibleNextCoords.x][possibleNextCoords.y] !== ".") {
guardDirection = directions[guardDirection].next;
} else {
guardLocation = possibleNextCoords;
nextGuardLocation = rows[possibleNextCoords.x][possibleNextCoords.y];
}
}
}
const part1 = (rows, guardLocation) => getPlacesVisited(rows, guardLocation).size;
const part2 = (rows, guardLocation) => {
// All the places the guard would normally visit (minus starting location)
const placesVisited = [...getPlacesVisited(rows, guardLocation)].slice(1);
let infiniteLoops = 0;
for (let i = 0; i < placesVisited.length; i++) {
const [ obstacleX, obstacleY ] = placesVisited[i].split(", ").map(Number);
// Temporarily change normal tile to obstacle
rows[obstacleX][obstacleY] = "#";
if (checkInfiniteLoop(rows, guardLocation)) infiniteLoops++;
// Return obstacle to normal tile
rows[obstacleX][obstacleY] = ".";
}
return infiniteLoops;
} | javascript |
2024 | 6 | 1 | --- Day 6: Guard Gallivant ---
The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians.
You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab.
Maybe you can work out where the guard will go ahead of time so that The Historians can search safely?
You start by making a map (your puzzle input) of the situation. For example:
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #.
Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps:
If there is something directly in front of you, turn right 90 degrees.
Otherwise, take a step forward.
Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes):
....#.....
....^....#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction:
....#.....
........>#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward:
....#.....
.........#
..........
..#.......
.......#..
..........
.#......v.
........#.
#.........
......#...
This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent):
....#.....
.........#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#v..
By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X:
....#.....
....XXXXX#
....X...X.
..#.X...X.
..XXXXX#X.
..X.X.X.X.
.#XXXXXXX.
.XXXXXXX#.
#XXXXXXX..
......#X..
In this example, the guard will visit 41 distinct positions on your map.
Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? | 4890 | const fs = require('fs');
// Directions: Up, Right, Down, Left
const DIRECTIONS = ['^', '>', 'v', '<'];
// Movement offsets for each direction
const MOVEMENT = {
'^': { dx: 0, dy: -1 }, // Up
'>': { dx: 1, dy: 0 }, // Right
'v': { dx: 0, dy: 1 }, // Down
'<': { dx: -1, dy: 0 }, // Left
};
// Function to find the guard's starting position and direction
const findGuard = (map) => {
for (let y = 0; y < map.length; y++) {
for (let x = 0; x < map[y].length; x++) {
if (DIRECTIONS.includes(map[y][x])) {
return { x, y, direction: map[y][x] };
}
}
}
throw new Error('Guard not found on the map!');
};
// Function to turn the guard 90 degrees to the right
const turnRight = (direction) => {
const currentIndex = DIRECTIONS.indexOf(direction);
return DIRECTIONS[(currentIndex + 1) % 4];
};
// Function to get the next position based on the current position and direction
const getNextPosition = (x, y, direction) => {
const { dx, dy } = MOVEMENT[direction];
return { x: x + dx, y: y + dy };
};
// Function to check if a position is within the map boundaries
const isWithinBounds = (x, y, map) => {
return x >= 0 && x < map[0].length && y >= 0 && y < map.length;
};
// Function to check if a position is an obstacle
const isObstacle = (x, y, map) => {
return map[y][x] === '#';
};
// Function to simulate the guard's movement
const simulateGuardMovement = (map) => {
const { x, y, direction } = findGuard(map);
let currentDirection = direction;
let currentPosition = { x, y };
const visited = new Set();
visited.add(`${currentPosition.x},${currentPosition.y}`);
while (true) {
const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection);
// Check if the guard is leaving the map
if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) {
break;
}
// Check if the next position is an obstacle
if (isObstacle(nextPosition.x, nextPosition.y, map)) {
currentDirection = turnRight(currentDirection); // Turn right
} else {
currentPosition = nextPosition; // Move forward
visited.add(`${currentPosition.x},${currentPosition.y}`);
}
}
return visited.size;
};
// Read the input file
const input = fs.readFileSync('input.txt', 'utf8').trim();
const map = input.split('\n');
// Simulate the guard's movement and print the result
const distinctPositions = simulateGuardMovement(map);
console.log(`Number of distinct positions visited: ${distinctPositions}`); | javascript |
2024 | 6 | 1 | --- Day 6: Guard Gallivant ---
The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians.
You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab.
Maybe you can work out where the guard will go ahead of time so that The Historians can search safely?
You start by making a map (your puzzle input) of the situation. For example:
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #.
Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps:
If there is something directly in front of you, turn right 90 degrees.
Otherwise, take a step forward.
Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes):
....#.....
....^....#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction:
....#.....
........>#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward:
....#.....
.........#
..........
..#.......
.......#..
..........
.#......v.
........#.
#.........
......#...
This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent):
....#.....
.........#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#v..
By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X:
....#.....
....XXXXX#
....X...X.
..#.X...X.
..XXXXX#X.
..X.X.X.X.
.#XXXXXXX.
.XXXXXXX#.
#XXXXXXX..
......#X..
In this example, the guard will visit 41 distinct positions on your map.
Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? | 4890 | const fs = require('fs');
// Class to represent the Guard
class Guard {
constructor(x, y, direction) {
this.x = x;
this.y = y;
this.direction = direction;
this.directions = ['^', '>', 'v', '<']; // Up, Right, Down, Left
this.movement = {
'^': { dx: 0, dy: -1 }, // Up
'>': { dx: 1, dy: 0 }, // Right
'v': { dx: 0, dy: 1 }, // Down
'<': { dx: -1, dy: 0 }, // Left
};
}
// Turn the guard 90 degrees to the right
turnRight() {
const currentIndex = this.directions.indexOf(this.direction);
this.direction = this.directions[(currentIndex + 1) % 4];
}
// Move the guard forward in the current direction
moveForward() {
const { dx, dy } = this.movement[this.direction];
this.x += dx;
this.y += dy;
}
// Get the next position without actually moving
getNextPosition() {
const { dx, dy } = this.movement[this.direction];
return { x: this.x + dx, y: this.y + dy };
}
}
// Class to represent the Map
class Map {
constructor(grid) {
this.grid = grid;
this.width = grid[0].length;
this.height = grid.length;
}
// Check if a position is within the map boundaries
isWithinBounds(x, y) {
return x >= 0 && x < this.width && y >= 0 && y < this.height;
}
// Check if a position is an obstacle
isObstacle(x, y) {
return this.grid[y][x] === '#';
}
// Find the guard's starting position and direction
findGuard() {
for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
if ('^>v<'.includes(this.grid[y][x])) {
return { x, y, direction: this.grid[y][x] };
}
}
}
throw new Error('Guard not found on the map!');
}
}
// Main function to simulate the guard's movement
function simulateGuardMovement(map) {
const guardMap = new Map(map);
const { x, y, direction } = guardMap.findGuard();
const guard = new Guard(x, y, direction);
const visited = new Set();
visited.add(`${guard.x},${guard.y}`);
while (true) {
const nextPosition = guard.getNextPosition();
// Check if the guard is leaving the map
if (!guardMap.isWithinBounds(nextPosition.x, nextPosition.y)) {
break;
}
// Check if the next position is an obstacle
if (guardMap.isObstacle(nextPosition.x, nextPosition.y)) {
guard.turnRight(); // Turn right if there's an obstacle
} else {
guard.moveForward(); // Move forward
visited.add(`${guard.x},${guard.y}`);
}
}
return visited.size;
}
// Read the input file
const input = fs.readFileSync('input.txt', 'utf8').trim();
const map = input.split('\n');
// Simulate the guard's movement and print the result
const distinctPositions = simulateGuardMovement(map);
console.log(`Number of distinct positions visited: ${distinctPositions}`); | javascript |
2024 | 6 | 1 | --- Day 6: Guard Gallivant ---
The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians.
You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab.
Maybe you can work out where the guard will go ahead of time so that The Historians can search safely?
You start by making a map (your puzzle input) of the situation. For example:
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #.
Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps:
If there is something directly in front of you, turn right 90 degrees.
Otherwise, take a step forward.
Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes):
....#.....
....^....#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction:
....#.....
........>#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward:
....#.....
.........#
..........
..#.......
.......#..
..........
.#......v.
........#.
#.........
......#...
This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent):
....#.....
.........#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#v..
By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X:
....#.....
....XXXXX#
....X...X.
..#.X...X.
..XXXXX#X.
..X.X.X.X.
.#XXXXXXX.
.XXXXXXX#.
#XXXXXXX..
......#X..
In this example, the guard will visit 41 distinct positions on your map.
Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? | 4890 | const fs = require('fs');
// Read the input file
const input = fs.readFileSync('input.txt', 'utf8');
// Parse the grid into a 2D array
let grid = input.split('\n').map(line => line.split(''));
const numRows = grid.length;
const numCols = grid[0].length;
// Define directions and their corresponding movements
const directions = ['up', 'right', 'down', 'left'];
const moves = {
'up': [-1, 0],
'right': [0, 1],
'down': [1, 0],
'left': [0, -1]
};
// Map symbols to directions
const dirSymbols = {
'^': 'up',
'>': 'right',
'v': 'down',
'<': 'left'
};
// Find the starting position and direction of the guard
let posRow, posCol, dir;
outerLoop:
for (let i = 0; i < numRows; i++) {
for (let j = 0; j < numCols; j++) {
let cell = grid[i][j];
if (cell in dirSymbols) {
posRow = i;
posCol = j;
dir = dirSymbols[cell];
grid[i][j] = '.'; // Replace the starting symbol with empty space
break outerLoop;
}
}
}
// Set to keep track of visited positions
let visited = new Set();
visited.add(`${posRow},${posCol}`);
while (true) {
// Compute the next position
let [dRow, dCol] = moves[dir];
let newRow = posRow + dRow;
let newCol = posCol + dCol;
// Check if the guard is about to leave the grid
if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) {
break;
}
let cellAhead = grid[newRow][newCol];
if (cellAhead === '#') {
// Turn right 90 degrees
let dirIndex = directions.indexOf(dir);
dirIndex = (dirIndex + 1) % 4;
dir = directions[dirIndex];
} else {
// Move forward
posRow = newRow;
posCol = newCol;
visited.add(`${posRow},${posCol}`);
}
}
// Output the number of distinct positions visited
console.log(visited.size); | javascript |
2024 | 6 | 2 | --- Day 6: Guard Gallivant ---
The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians.
You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab.
Maybe you can work out where the guard will go ahead of time so that The Historians can search safely?
You start by making a map (your puzzle input) of the situation. For example:
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #.
Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps:
If there is something directly in front of you, turn right 90 degrees.
Otherwise, take a step forward.
Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes):
....#.....
....^....#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction:
....#.....
........>#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward:
....#.....
.........#
..........
..#.......
.......#..
..........
.#......v.
........#.
#.........
......#...
This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent):
....#.....
.........#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#v..
By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X:
....#.....
....XXXXX#
....X...X.
..#.X...X.
..XXXXX#X.
..X.X.X.X.
.#XXXXXXX.
.XXXXXXX#.
#XXXXXXX..
......#X..
In this example, the guard will visit 41 distinct positions on your map.
Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?
Your puzzle answer was 4890.
--- Part Two ---
While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet.
Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught.
Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search.
To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice.
In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right.
Option one, put a printing press next to the guard's starting position:
....#.....
....+---+#
....|...|.
..#.|...|.
....|..#|.
....|...|.
.#.O^---+.
........#.
#.........
......#...
Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
......O.#.
#.........
......#...
Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----+O#.
#+----+...
......#...
Option four, put an alchemical retroencabulator near the bottom left corner:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
..|...|.#.
#O+---+...
......#...
Option five, put the alchemical retroencabulator a bit to the right instead:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
....|.|.#.
#..O+-+...
......#...
Option six, put a tank of sovereign glue right next to the tank of universal solvent:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----++#.
#+----++..
......#O..
It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose.
You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction? | 1995 | const fs = require('fs');
// Directions: Up, Right, Down, Left
const DIRECTIONS = ['^', '>', 'v', '<'];
// Movement offsets for each direction
const MOVEMENT = {
'^': { dx: 0, dy: -1 }, // Up
'>': { dx: 1, dy: 0 }, // Right
'v': { dx: 0, dy: 1 }, // Down
'<': { dx: -1, dy: 0 }, // Left
};
// Function to find the guard's starting position and direction
const findGuard = (map) => {
for (let y = 0; y < map.length; y++) {
for (let x = 0; x < map[y].length; x++) {
if (DIRECTIONS.includes(map[y][x])) {
return { x, y, direction: map[y][x] };
}
}
}
throw new Error('Guard not found on the map!');
};
// Function to turn the guard 90 degrees to the right
const turnRight = (direction) => {
const currentIndex = DIRECTIONS.indexOf(direction);
return DIRECTIONS[(currentIndex + 1) % 4];
};
// Function to get the next position based on the current position and direction
const getNextPosition = (x, y, direction) => {
const { dx, dy } = MOVEMENT[direction];
return { x: x + dx, y: y + dy };
};
// Function to check if a position is within the map boundaries
const isWithinBounds = (x, y, map) => {
return x >= 0 && x < map[0].length && y >= 0 && y < map.length;
};
// Function to check if a position is an obstacle
const isObstacle = (x, y, map) => {
return map[y][x] === '#';
};
// Function to simulate the guard's movement and check for loops
const simulateGuardMovement = (map, startX, startY, startDirection) => {
let currentDirection = startDirection;
let currentPosition = { x: startX, y: startY };
const visited = new Set();
visited.add(`${currentPosition.x},${currentPosition.y},${currentDirection}`);
while (true) {
const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection);
// Check if the guard is leaving the map
if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) {
return false; // No loop, guard leaves the map
}
// Check if the next position is an obstacle
if (isObstacle(nextPosition.x, nextPosition.y, map)) {
currentDirection = turnRight(currentDirection); // Turn right
} else {
currentPosition = nextPosition; // Move forward
const key = `${currentPosition.x},${currentPosition.y},${currentDirection}`;
// Check if the guard has been here before with the same direction
if (visited.has(key)) {
return true; // Loop detected
}
visited.add(key);
}
}
};
// Function to count valid obstruction positions
const countValidObstructionPositions = (map) => {
const { x: startX, y: startY, direction: startDirection } = findGuard(map);
let validPositions = 0;
for (let y = 0; y < map.length; y++) {
for (let x = 0; x < map[y].length; x++) {
// Skip the guard's starting position and non-empty positions
if ((x === startX && y === startY) || map[y][x] !== '.') {
continue;
}
// Create a copy of the map with the new obstruction
const newMap = map.map((row) => row.split(''));
newMap[y][x] = '#';
const newMapString = newMap.map((row) => row.join(''));
// Simulate the guard's movement and check for loops
if (simulateGuardMovement(newMapString, startX, startY, startDirection)) {
validPositions++;
}
}
}
return validPositions;
};
// Read the input file
const input = fs.readFileSync('input.txt', 'utf8').trim();
const map = input.split('\n');
// Count valid obstruction positions and print the result
const validPositions = countValidObstructionPositions(map);
console.log(`Number of valid obstruction positions: ${validPositions}`); | javascript |
2024 | 6 | 2 | --- Day 6: Guard Gallivant ---
The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians.
You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab.
Maybe you can work out where the guard will go ahead of time so that The Historians can search safely?
You start by making a map (your puzzle input) of the situation. For example:
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #.
Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps:
If there is something directly in front of you, turn right 90 degrees.
Otherwise, take a step forward.
Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes):
....#.....
....^....#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction:
....#.....
........>#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward:
....#.....
.........#
..........
..#.......
.......#..
..........
.#......v.
........#.
#.........
......#...
This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent):
....#.....
.........#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#v..
By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X:
....#.....
....XXXXX#
....X...X.
..#.X...X.
..XXXXX#X.
..X.X.X.X.
.#XXXXXXX.
.XXXXXXX#.
#XXXXXXX..
......#X..
In this example, the guard will visit 41 distinct positions on your map.
Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?
Your puzzle answer was 4890.
--- Part Two ---
While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet.
Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught.
Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search.
To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice.
In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right.
Option one, put a printing press next to the guard's starting position:
....#.....
....+---+#
....|...|.
..#.|...|.
....|..#|.
....|...|.
.#.O^---+.
........#.
#.........
......#...
Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
......O.#.
#.........
......#...
Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----+O#.
#+----+...
......#...
Option four, put an alchemical retroencabulator near the bottom left corner:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
..|...|.#.
#O+---+...
......#...
Option five, put the alchemical retroencabulator a bit to the right instead:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
....|.|.#.
#..O+-+...
......#...
Option six, put a tank of sovereign glue right next to the tank of universal solvent:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----++#.
#+----++..
......#O..
It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose.
You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction? | 1995 | const fs = require('fs');
// Constants for directions and movement offsets
const DIRECTIONS = ['^', '>', 'v', '<'];
const MOVEMENT = {
'^': { dx: 0, dy: -1 },
'>': { dx: 1, dy: 0 },
'v': { dx: 0, dy: 1 },
'<': { dx: -1, dy: 0 },
};
// Class representing the Guard
class Guard {
constructor(map) {
this.map = map;
const { x, y, direction } = this.findGuard();
this.position = { x, y };
this.direction = direction;
}
// Find the guard's initial position and direction
findGuard() {
for (let y = 0; y < this.map.length; y++) {
for (let x = 0; x < this.map[y].length; x++) {
if (DIRECTIONS.includes(this.map[y][x])) {
return { x, y, direction: this.map[y][x] };
}
}
}
throw new Error('Guard not found on the map!');
}
// Turn the guard 90 degrees to the right
turnRight() {
const index = DIRECTIONS.indexOf(this.direction);
this.direction = DIRECTIONS[(index + 1) % 4];
}
// Get the next position based on the current position and direction
getNextPosition() {
const { dx, dy } = MOVEMENT[this.direction];
return { x: this.position.x + dx, y: this.position.y + dy };
}
// Check if a position is within the map boundaries
isWithinBounds(x, y) {
return x >= 0 && x < this.map[0].length && y >= 0 && y < this.map.length;
}
// Check if a position is an obstacle
isObstacle(x, y) {
return this.map[y][x] === '#';
}
// Simulate the guard's movement
simulateMovement() {
const visited = new Set();
visited.add(`${this.position.x},${this.position.y},${this.direction}`);
while (true) {
const nextPosition = this.getNextPosition();
// Check if the guard is leaving the map
if (!this.isWithinBounds(nextPosition.x, nextPosition.y)) {
return false; // Guard exits the map
}
// Check if the next position is an obstacle
if (this.isObstacle(nextPosition.x, nextPosition.y)) {
this.turnRight(); // Turn right if there's an obstacle
} else {
this.position = nextPosition; // Move forward
const key = `${this.position.x},${this.position.y},${this.direction}`;
// Check if the guard has been here before
if (visited.has(key)) {
return true; // Loop detected
}
visited.add(key);
}
}
}
}
// Class to solve the problem
class Solution {
constructor(filePath) {
this.map = this.readInput(filePath);
this.guard = new Guard(this.map);
}
// Read the input file and parse the map
readInput(filePath) {
return fs.readFileSync(filePath, 'utf8').trim().split('\n');
}
// Count valid obstruction positions
countValidObstructionPositions() {
const { x: startX, y: startY } = this.guard.position;
let validPositions = 0;
for (let y = 0; y < this.map.length; y++) {
for (let x = 0; x < this.map[y].length; x++) {
// Skip the guard's starting position and non-empty positions
if ((x === startX && y === startY) || this.map[y][x] !== '.') {
continue;
}
// Create a copy of the map with the new obstruction
const newMap = this.map.map((row) => row.split(''));
newMap[y][x] = '#';
const newMapString = newMap.map((row) => row.join(''));
// Simulate the guard's movement and check for loops
const guardWithNewMap = new Guard(newMapString);
if (guardWithNewMap.simulateMovement()) {
validPositions++;
}
}
}
return validPositions;
}
// Main method to solve the problem
solve() {
const validPositions = this.countValidObstructionPositions();
console.log(`Number of valid obstruction positions: ${validPositions}`);
}
}
// Instantiate the solution class and solve the problem
const solution = new Solution('input.txt');
solution.solve(); | javascript |
2024 | 6 | 2 | --- Day 6: Guard Gallivant ---
The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians.
You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab.
Maybe you can work out where the guard will go ahead of time so that The Historians can search safely?
You start by making a map (your puzzle input) of the situation. For example:
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #.
Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps:
If there is something directly in front of you, turn right 90 degrees.
Otherwise, take a step forward.
Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes):
....#.....
....^....#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction:
....#.....
........>#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward:
....#.....
.........#
..........
..#.......
.......#..
..........
.#......v.
........#.
#.........
......#...
This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent):
....#.....
.........#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#v..
By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X:
....#.....
....XXXXX#
....X...X.
..#.X...X.
..XXXXX#X.
..X.X.X.X.
.#XXXXXXX.
.XXXXXXX#.
#XXXXXXX..
......#X..
In this example, the guard will visit 41 distinct positions on your map.
Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?
Your puzzle answer was 4890.
--- Part Two ---
While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet.
Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught.
Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search.
To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice.
In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right.
Option one, put a printing press next to the guard's starting position:
....#.....
....+---+#
....|...|.
..#.|...|.
....|..#|.
....|...|.
.#.O^---+.
........#.
#.........
......#...
Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
......O.#.
#.........
......#...
Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----+O#.
#+----+...
......#...
Option four, put an alchemical retroencabulator near the bottom left corner:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
..|...|.#.
#O+---+...
......#...
Option five, put the alchemical retroencabulator a bit to the right instead:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
....|.|.#.
#..O+-+...
......#...
Option six, put a tank of sovereign glue right next to the tank of universal solvent:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----++#.
#+----++..
......#O..
It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose.
You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction? | 1995 | const fs = require('fs');
const {log} = require('console');
let lines = fs.readFileSync('input.txt', 'utf-8').split('\n');
function findPosition() {
for (let i = 0; i < lines.length; i++) {
for (let j = 0; j < lines[0].length; j++) {
if (lines[i][j] === '^') {
return [j, i];
}
}
}
}
let [columnStart, rowStart] = findPosition();
let [columnCurrent, rowCurrent] = [columnStart, rowStart];
let [columnDirection, rowDirection] = [0, -1];
let visited = new Set();
const key = (c, r) => `${c},${r}`;
visited.add(key(columnStart, rowStart));
while (true) {
let [columnNext, rowNext] = [columnCurrent + columnDirection, rowCurrent + rowDirection];
if (columnNext < 0 || rowNext < 0 || columnNext >= lines[0].length || rowNext >= lines.length) {
break;
}
if (lines[rowNext][columnNext] === '#') {
// turn right
[columnDirection, rowDirection] = [-rowDirection, columnDirection];
} else {
visited.add(key(columnNext, rowNext));
[columnCurrent, rowCurrent] = [columnNext, rowNext];
}
}
log(visited.size);
function isEndless(columnStart, rowStart, columnDirection, rowDirection, grid) {
let [columnCurrent, rowCurrent] = [columnStart, rowStart];
let visited = {};
visited[key(columnStart, rowStart)] = [[columnDirection, rowDirection]];
while (true) {
let [columnNext, rowNext] = [columnCurrent + columnDirection, rowCurrent + rowDirection];
if (columnNext < 0 || rowNext < 0 || columnNext >= lines[0].length || rowNext >= lines.length) {
return false;
}
if (grid[rowNext][columnNext] === '#') {
// turn right
[columnDirection, rowDirection] = [-rowDirection, columnDirection];
} else {
let k = key(columnNext, rowNext);
let dk = key(columnDirection, rowDirection);
if (visited[k]) {
if (visited[k].includes(dk)) {
// loop confirmed
return true;
}
visited[k].push(dk);
} else {
visited[k] = [dk];
}
[columnCurrent, rowCurrent] = [columnNext, rowNext];
}
}
}
// part 2
let blocks = new Set();
// change every visited coordinate (except start) to # and check if it results in a loop.
for (let k of visited) {
const [c, r] = k.split(',').map(x => parseInt(x))
if (!(c === columnStart && r === rowStart)) {
// clone grid with added # on next direction and check isEndless
const copy = JSON.parse(JSON.stringify(lines));
copy[r] = copy[r].slice(0, c) + '#' + copy[r].slice(c + 1);
if (isEndless(columnStart, rowStart, -1, 0, copy)) {
blocks.add(key(c, r));
}
}
}
console.log(blocks.size); | javascript |
2024 | 6 | 2 | --- Day 6: Guard Gallivant ---
The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians.
You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab.
Maybe you can work out where the guard will go ahead of time so that The Historians can search safely?
You start by making a map (your puzzle input) of the situation. For example:
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #.
Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps:
If there is something directly in front of you, turn right 90 degrees.
Otherwise, take a step forward.
Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes):
....#.....
....^....#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction:
....#.....
........>#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward:
....#.....
.........#
..........
..#.......
.......#..
..........
.#......v.
........#.
#.........
......#...
This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent):
....#.....
.........#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#v..
By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X:
....#.....
....XXXXX#
....X...X.
..#.X...X.
..XXXXX#X.
..X.X.X.X.
.#XXXXXXX.
.XXXXXXX#.
#XXXXXXX..
......#X..
In this example, the guard will visit 41 distinct positions on your map.
Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?
Your puzzle answer was 4890.
--- Part Two ---
While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet.
Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught.
Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search.
To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice.
In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right.
Option one, put a printing press next to the guard's starting position:
....#.....
....+---+#
....|...|.
..#.|...|.
....|..#|.
....|...|.
.#.O^---+.
........#.
#.........
......#...
Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
......O.#.
#.........
......#...
Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----+O#.
#+----+...
......#...
Option four, put an alchemical retroencabulator near the bottom left corner:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
..|...|.#.
#O+---+...
......#...
Option five, put the alchemical retroencabulator a bit to the right instead:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
....|.|.#.
#..O+-+...
......#...
Option six, put a tank of sovereign glue right next to the tank of universal solvent:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----++#.
#+----++..
......#O..
It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose.
You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction? | 1995 | const fs = require('fs');
// Read the input file
const input = fs.readFileSync('input.txt', 'utf8');
// Parse the grid into a 2D array
let originalGrid = input.split('\n').map(line => line.split(''));
const numRows = originalGrid.length;
const numCols = originalGrid[0].length;
// Define directions and their corresponding movements
const directions = ['up', 'right', 'down', 'left'];
const moves = {
'up': [-1, 0],
'right': [0, 1],
'down': [1, 0],
'left': [0, -1]
};
// Map symbols to directions
const dirSymbols = {
'^': 'up',
'>': 'right',
'v': 'down',
'<': 'left'
};
// Find the starting position and direction of the guard
let startRow, startCol, startDir;
outerLoop:
for (let i = 0; i < numRows; i++) {
for (let j = 0; j < numCols; j++) {
let cell = originalGrid[i][j];
if (cell in dirSymbols) {
startRow = i;
startCol = j;
startDir = dirSymbols[cell];
break outerLoop;
}
}
}
// Function to simulate the guard's movement
function simulate(grid) {
let posRow = startRow;
let posCol = startCol;
let dir = startDir;
// Visited positions with direction
let visitedStates = new Set();
visitedStates.add(`${posRow},${posCol},${dir}`);
while (true) {
let [dRow, dCol] = moves[dir];
let newRow = posRow + dRow;
let newCol = posCol + dCol;
// Check if the guard is about to leave the grid
if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) {
return false; // Guard leaves the grid
}
let cellAhead = grid[newRow][newCol];
if (cellAhead === '#') {
// Turn right 90 degrees
let dirIndex = directions.indexOf(dir);
dirIndex = (dirIndex + 1) % 4;
dir = directions[dirIndex];
} else {
// Move forward
posRow = newRow;
posCol = newCol;
}
let state = `${posRow},${posCol},${dir}`;
if (visitedStates.has(state)) {
return true; // Guard is in a loop
}
visitedStates.add(state);
}
}
// Count the number of positions where adding an obstruction causes the guard to loop
let count = 0;
for (let i = 0; i < numRows; i++) {
for (let j = 0; j < numCols; j++) {
// Skip if cell is not empty or is the starting position
if (originalGrid[i][j] !== '.' || (i === startRow && j === startCol)) {
continue;
}
// Create a copy of the grid
let grid = originalGrid.map(row => row.slice());
// Place an obstruction at (i, j)
grid[i][j] = '#';
// Simulate the guard's movement
if (simulate(grid)) {
count++;
}
}
}
// Output the total count
console.log(count); | javascript |
2024 | 6 | 2 | --- Day 6: Guard Gallivant ---
The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians.
You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab.
Maybe you can work out where the guard will go ahead of time so that The Historians can search safely?
You start by making a map (your puzzle input) of the situation. For example:
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #.
Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps:
If there is something directly in front of you, turn right 90 degrees.
Otherwise, take a step forward.
Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes):
....#.....
....^....#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction:
....#.....
........>#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward:
....#.....
.........#
..........
..#.......
.......#..
..........
.#......v.
........#.
#.........
......#...
This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent):
....#.....
.........#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#v..
By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X:
....#.....
....XXXXX#
....X...X.
..#.X...X.
..XXXXX#X.
..X.X.X.X.
.#XXXXXXX.
.XXXXXXX#.
#XXXXXXX..
......#X..
In this example, the guard will visit 41 distinct positions on your map.
Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?
Your puzzle answer was 4890.
--- Part Two ---
While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet.
Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught.
Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search.
To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice.
In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right.
Option one, put a printing press next to the guard's starting position:
....#.....
....+---+#
....|...|.
..#.|...|.
....|..#|.
....|...|.
.#.O^---+.
........#.
#.........
......#...
Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
......O.#.
#.........
......#...
Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----+O#.
#+----+...
......#...
Option four, put an alchemical retroencabulator near the bottom left corner:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
..|...|.#.
#O+---+...
......#...
Option five, put the alchemical retroencabulator a bit to the right instead:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
....|.|.#.
#..O+-+...
......#...
Option six, put a tank of sovereign glue right next to the tank of universal solvent:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----++#.
#+----++..
......#O..
It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose.
You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction? | 1995 | const fs = require('fs');
// Constants for directions and movement offsets
const DIRECTIONS = ['^', '>', 'v', '<'];
const MOVEMENT = {
'^': { dx: 0, dy: -1 }, // Up
'>': { dx: 1, dy: 0 }, // Right
'v': { dx: 0, dy: 1 }, // Down
'<': { dx: -1, dy: 0 }, // Left
};
// Read the input file and parse the map
const readInput = (filePath) => {
return fs.readFileSync(filePath, 'utf8').trim().split('\n');
};
// Find the guard's starting position and direction
const findGuard = (map) => {
for (let y = 0; y < map.length; y++) {
for (let x = 0; x < map[y].length; x++) {
if (DIRECTIONS.includes(map[y][x])) {
return { x, y, direction: map[y][x] };
}
}
}
throw new Error('Guard not found on the map!');
};
// Turn the guard 90 degrees to the right
const turnRight = (direction) => {
const currentIndex = DIRECTIONS.indexOf(direction);
return DIRECTIONS[(currentIndex + 1) % 4];
};
// Get the next position based on the current position and direction
const getNextPosition = (x, y, direction) => {
const { dx, dy } = MOVEMENT[direction];
return { x: x + dx, y: y + dy };
};
// Check if a position is within the map boundaries
const isWithinBounds = (x, y, map) => {
return x >= 0 && x < map[0].length && y >= 0 && y < map.length;
};
// Check if a position is an obstacle
const isObstacle = (x, y, map) => {
return map[y][x] === '#';
};
// Simulate the guard's movement and check for loops
const simulateGuardMovement = (map, startX, startY, startDirection) => {
let currentDirection = startDirection;
let currentPosition = { x: startX, y: startY };
const visited = new Set();
visited.add(`${currentPosition.x},${currentPosition.y},${currentDirection}`);
while (true) {
const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection);
// Check if the guard is leaving the map
if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) {
return false; // No loop, guard leaves the map
}
// Check if the next position is an obstacle
if (isObstacle(nextPosition.x, nextPosition.y, map)) {
currentDirection = turnRight(currentDirection); // Turn right
} else {
currentPosition = nextPosition; // Move forward
const key = `${currentPosition.x},${currentPosition.y},${currentDirection}`;
// Check if the guard has been here before with the same direction
if (visited.has(key)) {
return true; // Loop detected
}
visited.add(key);
}
}
};
// Count valid obstruction positions
const countValidObstructionPositions = (map) => {
const { x: startX, y: startY, direction: startDirection } = findGuard(map);
let validPositions = 0;
for (let y = 0; y < map.length; y++) {
for (let x = 0; x < map[y].length; x++) {
// Skip the guard's starting position and non-empty positions
if ((x === startX && y === startY) || map[y][x] !== '.') {
continue;
}
// Create a copy of the map with the new obstruction
const newMap = map.map((row) => row.split(''));
newMap[y][x] = '#';
const newMapString = newMap.map((row) => row.join(''));
// Simulate the guard's movement and check for loops
if (simulateGuardMovement(newMapString, startX, startY, startDirection)) {
validPositions++;
}
}
}
return validPositions;
};
// Main function to solve the problem
const solve = (filePath) => {
const map = readInput(filePath);
const validPositions = countValidObstructionPositions(map);
console.log(`Number of valid obstruction positions: ${validPositions}`);
};
// Run the solution
solve('input.txt'); | javascript |
2024 | 8 | 1 | --- Day 8: Resonant Collinearity ---
You find yourselves on the roof of a top-secret Easter Bunny installation.
While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable!
Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example:
............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............
The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them.
So, for these two antennas with frequency a, they create the two antinodes marked with #:
..........
...#......
..........
....a.....
..........
.....a....
..........
......#...
..........
..........
Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......#...
..........
..........
Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......A...
..........
..........
The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna:
......#....#
...#....0...
....#0....#.
..#....0....
....0....#..
.#....A.....
...#........
#......#....
........A...
.........A..
..........#.
..........#.
Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map.
Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? | 332 | const fs = require('fs');
const input = fs.readFileSync('input.txt', 'utf8').trim();
const lines = input.split('\n');
const height = lines.length;
const width = lines[0].length;
const antennas = {};
// Collect antennas by frequency
for (let y = 0; y < height; y++) {
const line = lines[y];
for (let x = 0; x < width; x++) {
const char = line[x];
if (/[a-zA-Z0-9]/.test(char)) {
if (!antennas[char]) antennas[char] = [];
antennas[char].push({ x, y });
}
}
}
const antinodes = new Set();
for (const freq in antennas) {
const positions = antennas[freq];
const n = positions.length;
for (let i = 0; i < n; i++) {
const A = positions[i];
for (let j = i + 1; j < n; j++) {
const B = positions[j];
const dx = A.x - B.x;
const dy = A.y - B.y;
const D = { x: dx, y: dy };
// Antinodes occur at positions where one antenna is twice as far as the other
const tValues = [-1, 2];
for (const t of tValues) {
const Px = B.x + t * D.x;
const Py = B.y + t * D.y;
if (
Number.isInteger(Px) &&
Number.isInteger(Py) &&
Px >= 0 &&
Px < width &&
Py >= 0 &&
Py < height
) {
const key = `${Px},${Py}`;
antinodes.add(key);
}
}
}
}
}
console.log(antinodes.size); | javascript |
2024 | 8 | 1 | --- Day 8: Resonant Collinearity ---
You find yourselves on the roof of a top-secret Easter Bunny installation.
While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable!
Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example:
............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............
The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them.
So, for these two antennas with frequency a, they create the two antinodes marked with #:
..........
...#......
..........
....a.....
..........
.....a....
..........
......#...
..........
..........
Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......#...
..........
..........
Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......A...
..........
..........
The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna:
......#....#
...#....0...
....#0....#.
..#....0....
....0....#..
.#....A.....
...#........
#......#....
........A...
.........A..
..........#.
..........#.
Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map.
Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? | 332 | const fs = require('fs');
// Read and parse the input file
const input = fs.readFileSync('input.txt', 'utf8').trim();
const mapLines = input.split('\n');
const mapHeight = mapLines.length;
const mapWidth = mapLines[0].length;
// Function to locate antennas by frequency in the map
function extractAntennas(mapLines) {
const antennas = {};
mapLines.forEach((line, y) => {
Array.from(line).forEach((char, x) => {
if (/[a-zA-Z0-9]/.test(char)) {
if (!antennas[char]) {
antennas[char] = [];
}
antennas[char].push({ x, y });
}
});
});
return antennas;
}
// Function to calculate all antinode positions
function findAntinodePositions(antennas, mapWidth, mapHeight) {
const antinodes = new Set();
Object.entries(antennas).forEach(([freq, positions]) => {
for (let i = 0; i < positions.length; i++) {
const firstPos = positions[i];
for (let j = i + 1; j < positions.length; j++) {
const secondPos = positions[j];
// Calculate the difference between the two positions
const dx = firstPos.x - secondPos.x;
const dy = firstPos.y - secondPos.y;
// Check for potential antinodes
[-1, 2].forEach(t => {
const Px = secondPos.x + t * dx;
const Py = secondPos.y + t * dy;
// Check if the calculated position is within bounds
if (Px >= 0 && Px < mapWidth && Py >= 0 && Py < mapHeight && Number.isInteger(Px) && Number.isInteger(Py)) {
antinodes.add(`${Px},${Py}`);
}
});
}
}
});
return antinodes;
}
// Main execution function
function main() {
const antennas = extractAntennas(mapLines);
const antinodes = findAntinodePositions(antennas, mapWidth, mapHeight);
console.log(antinodes.size);
}
main(); | javascript |
2024 | 8 | 1 | --- Day 8: Resonant Collinearity ---
You find yourselves on the roof of a top-secret Easter Bunny installation.
While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable!
Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example:
............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............
The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them.
So, for these two antennas with frequency a, they create the two antinodes marked with #:
..........
...#......
..........
....a.....
..........
.....a....
..........
......#...
..........
..........
Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......#...
..........
..........
Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......A...
..........
..........
The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna:
......#....#
...#....0...
....#0....#.
..#....0....
....0....#..
.#....A.....
...#........
#......#....
........A...
.........A..
..........#.
..........#.
Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map.
Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? | 332 | const fs = require('fs');
// Read input file and split into lines
const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n');
// Parse the map into a grid of characters
const grid = input.map(line => line.split(''));
// Function to calculate the greatest common divisor (GCD) of two numbers
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
// Function to calculate all unique antinode positions
const calculateAntinodes = (grid) => {
const antinodes = new Set();
const rows = grid.length;
const cols = grid[0].length;
// Iterate over all pairs of antennas
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const frequency1 = grid[i][j];
if (frequency1 === '.') continue; // Skip empty spaces
for (let k = 0; k < rows; k++) {
for (let l = 0; l < cols; l++) {
const frequency2 = grid[k][l];
if (frequency2 !== frequency1 || (i === k && j === l)) continue; // Skip same antenna or different frequencies
// Calculate the differences in positions
const dx = k - i;
const dy = l - j;
// Calculate the GCD to simplify the direction vector
const divisor = gcd(Math.abs(dx), Math.abs(dy));
const stepX = dx / divisor;
const stepY = dy / divisor;
// Calculate the two antinode positions
const antinode1X = i - stepX;
const antinode1Y = j - stepY;
const antinode2X = k + stepX;
const antinode2Y = l + stepY;
// Check if the antinodes are within the grid bounds
if (antinode1X >= 0 && antinode1X < rows && antinode1Y >= 0 && antinode1Y < cols) {
antinodes.add(`${antinode1X},${antinode1Y}`);
}
if (antinode2X >= 0 && antinode2X < rows && antinode2Y >= 0 && antinode2Y < cols) {
antinodes.add(`${antinode2X},${antinode2Y}`);
}
}
}
}
}
return antinodes.size;
};
// Calculate and print the number of unique antinode locations
console.log(calculateAntinodes(grid)); | javascript |
2024 | 8 | 1 | --- Day 8: Resonant Collinearity ---
You find yourselves on the roof of a top-secret Easter Bunny installation.
While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable!
Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example:
............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............
The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them.
So, for these two antennas with frequency a, they create the two antinodes marked with #:
..........
...#......
..........
....a.....
..........
.....a....
..........
......#...
..........
..........
Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......#...
..........
..........
Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......A...
..........
..........
The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna:
......#....#
...#....0...
....#0....#.
..#....0....
....0....#..
.#....A.....
...#........
#......#....
........A...
.........A..
..........#.
..........#.
Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map.
Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? | 332 | const fs = require('fs');
// Utility function to read and split input into lines
function getInput(filePath) {
return fs.readFileSync(filePath, 'utf8').trim().split('\n');
}
// Utility function to find antennas by frequency
function findAntennas(lines) {
const antennas = {};
lines.forEach((line, y) => {
Array.from(line).forEach((char, x) => {
if (/[a-zA-Z0-9]/.test(char)) {
antennas[char] = antennas[char] || [];
antennas[char].push({ x, y });
}
});
});
return antennas;
}
// Function to calculate antinodes from antenna pairs
function calculateAntinodes(antennas, width, height) {
const antinodes = new Set();
Object.keys(antennas).forEach((freq) => {
const positions = antennas[freq];
const n = positions.length;
for (let i = 0; i < n; i++) {
const A = positions[i];
for (let j = i + 1; j < n; j++) {
const B = positions[j];
const dx = A.x - B.x;
const dy = A.y - B.y;
// Check antinode conditions for both t = -1 and t = 2
[-1, 2].forEach((t) => {
const Px = B.x + t * dx;
const Py = B.y + t * dy;
// Ensure that Px and Py are within bounds and valid positions
if (Number.isInteger(Px) && Number.isInteger(Py) &&
Px >= 0 && Px < width && Py >= 0 && Py < height) {
const key = `${Px},${Py}`;
antinodes.add(key);
}
});
}
}
});
return antinodes;
}
// Main function to execute the solution
function solve(filePath) {
const lines = getInput(filePath);
const height = lines.length;
const width = lines[0].length;
const antennas = findAntennas(lines);
const antinodes = calculateAntinodes(antennas, width, height);
console.log(antinodes.size);
}
// Run the solution
solve('input.txt'); | javascript |
2024 | 8 | 1 | --- Day 8: Resonant Collinearity ---
You find yourselves on the roof of a top-secret Easter Bunny installation.
While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable!
Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example:
............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............
The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them.
So, for these two antennas with frequency a, they create the two antinodes marked with #:
..........
...#......
..........
....a.....
..........
.....a....
..........
......#...
..........
..........
Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......#...
..........
..........
Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......A...
..........
..........
The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna:
......#....#
...#....0...
....#0....#.
..#....0....
....0....#..
.#....A.....
...#........
#......#....
........A...
.........A..
..........#.
..........#.
Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map.
Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? | 332 | const fs = require('fs');
// Read and parse the input file into a grid
const grid = fs.readFileSync('input.txt', 'utf8')
.trim()
.split('\n')
.map(line => line.split(''));
// Helper function to compute the greatest common divisor (GCD)
const computeGCD = (a, b) => b === 0 ? a : computeGCD(b, a % b);
// Function to find all unique antinode positions
const findAntinodes = (grid) => {
const rows = grid.length;
const cols = grid[0].length;
const antinodeSet = new Set();
// Iterate through all pairs of antennas
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const freq1 = grid[i][j];
if (freq1 === '.') continue; // Skip empty spaces
for (let k = 0; k < rows; k++) {
for (let l = 0; l < cols; l++) {
const freq2 = grid[k][l];
if (freq2 !== freq1 || (i === k && j === l)) continue; // Skip same antenna or different frequencies
// Calculate the direction vector between the two antennas
const deltaX = k - i;
const deltaY = l - j;
const gcd = computeGCD(Math.abs(deltaX), Math.abs(deltaY));
const stepX = deltaX / gcd;
const stepY = deltaY / gcd;
// Calculate the two antinode positions
const antinode1 = { x: i - stepX, y: j - stepY };
const antinode2 = { x: k + stepX, y: l + stepY };
// Check if the antinodes are within the grid bounds
if (antinode1.x >= 0 && antinode1.x < rows && antinode1.y >= 0 && antinode1.y < cols) {
antinodeSet.add(`${antinode1.x},${antinode1.y}`);
}
if (antinode2.x >= 0 && antinode2.x < rows && antinode2.y >= 0 && antinode2.y < cols) {
antinodeSet.add(`${antinode2.x},${antinode2.y}`);
}
}
}
}
}
return antinodeSet.size;
};
// Main function to calculate and log the result
const main = () => {
const antinodeCount = findAntinodes(grid);
console.log(antinodeCount);
};
// Execute the main function
main(); | javascript |
2024 | 8 | 2 | --- Day 8: Resonant Collinearity ---
You find yourselves on the roof of a top-secret Easter Bunny installation.
While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable!
Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example:
............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............
The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them.
So, for these two antennas with frequency a, they create the two antinodes marked with #:
..........
...#......
..........
....a.....
..........
.....a....
..........
......#...
..........
..........
Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......#...
..........
..........
Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......A...
..........
..........
The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna:
......#....#
...#....0...
....#0....#.
..#....0....
....0....#..
.#....A.....
...#........
#......#....
........A...
.........A..
..........#.
..........#.
Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map.
Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?
Your puzzle answer was 332.
--- Part Two ---
Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations.
Whoops!
After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency).
So, these three T-frequency antennas now create many antinodes:
T....#....
...T......
.T....#...
.........#
..#.......
..........
...#......
..........
....#.....
..........
In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9.
The original example now has 34 antinodes, including the antinodes that appear on every antenna:
##....#....#
.#.#....0...
..#.#0....#.
..##...0....
....0....#..
.#...#A....#
...#..#.....
#....#.#....
..#.....A...
....#....A..
.#........#.
...#......##
Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode? | 1174 | const fs = require('fs');
const grid = fs.readFileSync('input.txt', 'utf8').trim().split('\n').map(line => line.split(''));
const rows = grid.length;
const cols = grid[0].length;
const computeGCD = (a, b) => b === 0 ? a : computeGCD(b, a % b);
const findAntinodes = (grid) => {
const antinodeSet = new Set();
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const freq1 = grid[i][j];
if (freq1 === '.') continue;
for (let k = 0; k < rows; k++) {
for (let l = 0; l < cols; l++) {
const freq2 = grid[k][l];
if (freq2 !== freq1 || (i === k && j === l)) continue;
const deltaX = k - i;
const deltaY = l - j;
const gcd = computeGCD(Math.abs(deltaX), Math.abs(deltaY));
const stepX = deltaX / gcd;
const stepY = deltaY / gcd;
let x = i + stepX;
let y = j + stepY;
while (x >= 0 && x < rows && y >= 0 && y < cols) {
antinodeSet.add(`${x},${y}`);
x += stepX;
y += stepY;
}
x = i - stepX;
y = j - stepY;
while (x >= 0 && x < rows && y >= 0 && y < cols) {
antinodeSet.add(`${x},${y}`);
x -= stepX;
y -= stepY;
}
}
}
}
}
return antinodeSet.size;
};
console.log(findAntinodes(grid)); | javascript |
2024 | 8 | 2 | --- Day 8: Resonant Collinearity ---
You find yourselves on the roof of a top-secret Easter Bunny installation.
While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable!
Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example:
............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............
The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them.
So, for these two antennas with frequency a, they create the two antinodes marked with #:
..........
...#......
..........
....a.....
..........
.....a....
..........
......#...
..........
..........
Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......#...
..........
..........
Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......A...
..........
..........
The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna:
......#....#
...#....0...
....#0....#.
..#....0....
....0....#..
.#....A.....
...#........
#......#....
........A...
.........A..
..........#.
..........#.
Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map.
Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?
Your puzzle answer was 332.
--- Part Two ---
Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations.
Whoops!
After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency).
So, these three T-frequency antennas now create many antinodes:
T....#....
...T......
.T....#...
.........#
..#.......
..........
...#......
..........
....#.....
..........
In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9.
The original example now has 34 antinodes, including the antinodes that appear on every antenna:
##....#....#
.#.#....0...
..#.#0....#.
..##...0....
....0....#..
.#...#A....#
...#..#.....
#....#.#....
..#.....A...
....#....A..
.#........#.
...#......##
Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode? | 1174 | const fs = require('fs');
// Load the grid from the input file
const loadGrid = (filePath) => {
return fs.readFileSync(filePath, 'utf8')
.trim()
.split('\n')
.map(row => row.split(''));
};
// Calculate the greatest common divisor (GCD) of two numbers
const gcd = (a, b) => {
while (b !== 0) [a, b] = [b, a % b];
return a;
};
// Find all unique antinode positions in the grid
const findAntinodes = (grid) => {
const rows = grid.length;
const cols = grid[0].length;
const antinodes = new Set();
// Iterate through all pairs of antennas
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const freq = grid[i][j];
if (freq === '.') continue; // Skip empty spaces
for (let k = 0; k < rows; k++) {
for (let l = 0; l < cols; l++) {
if (grid[k][l] !== freq || (i === k && j === l)) continue; // Skip same antenna or different frequencies
// Calculate the direction vector
const dx = k - i;
const dy = l - j;
const divisor = gcd(Math.abs(dx), Math.abs(dy));
const stepX = dx / divisor;
const stepY = dy / divisor;
// Traverse in the direction of the vector
let x = i + stepX;
let y = j + stepY;
while (x >= 0 && x < rows && y >= 0 && y < cols) {
antinodes.add(`${x},${y}`);
x += stepX;
y += stepY;
}
// Traverse in the opposite direction
x = i - stepX;
y = j - stepY;
while (x >= 0 && x < rows && y >= 0 && y < cols) {
antinodes.add(`${x},${y}`);
x -= stepX;
y -= stepY;
}
}
}
}
}
return antinodes.size;
};
// Main function to execute the solution
const main = () => {
const grid = loadGrid('input.txt');
const result = findAntinodes(grid);
console.log(result);
};
// Run the program
main(); | javascript |
2024 | 8 | 2 | --- Day 8: Resonant Collinearity ---
You find yourselves on the roof of a top-secret Easter Bunny installation.
While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable!
Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example:
............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............
The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them.
So, for these two antennas with frequency a, they create the two antinodes marked with #:
..........
...#......
..........
....a.....
..........
.....a....
..........
......#...
..........
..........
Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......#...
..........
..........
Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......A...
..........
..........
The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna:
......#....#
...#....0...
....#0....#.
..#....0....
....0....#..
.#....A.....
...#........
#......#....
........A...
.........A..
..........#.
..........#.
Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map.
Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?
Your puzzle answer was 332.
--- Part Two ---
Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations.
Whoops!
After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency).
So, these three T-frequency antennas now create many antinodes:
T....#....
...T......
.T....#...
.........#
..#.......
..........
...#......
..........
....#.....
..........
In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9.
The original example now has 34 antinodes, including the antinodes that appear on every antenna:
##....#....#
.#.#....0...
..#.#0....#.
..##...0....
....0....#..
.#...#A....#
...#..#.....
#....#.#....
..#.....A...
....#....A..
.#........#.
...#......##
Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode? | 1174 | const fs = require('fs');
// Helper function to compute the greatest common divisor (GCD) of two numbers
const computeGCD = (a, b) => {
while (b !== 0) {
[a, b] = [b, a % b];
}
return Math.abs(a);
};
// Function to extract antennas from the input grid and organize them by frequency
const parseAntennas = (grid) => {
const antennas = {};
grid.forEach((line, y) => {
[...line].forEach((char, x) => {
if (/[a-zA-Z0-9]/.test(char)) {
if (!antennas[char]) {
antennas[char] = [];
}
antennas[char].push({ x, y });
}
});
});
return antennas;
};
// Function to gather all unique antinode positions in the grid
const calculateAntinodes = (antennas, width, height) => {
const antinodes = new Set();
Object.entries(antennas).forEach(([freq, positions]) => {
const numPositions = positions.length;
for (let i = 0; i < numPositions; i++) {
const first = positions[i];
for (let j = i + 1; j < numPositions; j++) {
const second = positions[j];
let dx = second.x - first.x;
let dy = second.y - first.y;
// Reduce the differences by the greatest common divisor (gcd)
const gcdValue = computeGCD(dx, dy);
dx /= gcdValue;
dy /= gcdValue;
// Add antinodes along the line in both directions
addAntinodesAlongLine(first.x, first.y, dx, dy, width, height, antinodes);
addAntinodesAlongLine(first.x - dx, first.y - dy, -dx, -dy, width, height, antinodes);
}
}
});
return antinodes;
};
// Function to add antinode positions along a specific line direction
const addAntinodesAlongLine = (startX, startY, dx, dy, width, height, antinodes) => {
let x = startX;
let y = startY;
// Add positions while moving along the line
while (x >= 0 && x < width && y >= 0 && y < height) {
const key = `${x},${y}`;
antinodes.add(key);
x += dx;
y += dy;
}
};
// Main execution function
const main = () => {
const input = fs.readFileSync('input.txt', 'utf8').trim();
const grid = input.split('\n');
const height = grid.length;
const width = grid[0].length;
// Parse the antennas from the grid
const antennas = parseAntennas(grid);
// Calculate all unique antinode positions
const antinodes = calculateAntinodes(antennas, width, height);
// Output the number of unique antinodes
console.log(antinodes.size);
};
// Run the program
main(); | javascript |
2024 | 8 | 2 | --- Day 8: Resonant Collinearity ---
You find yourselves on the roof of a top-secret Easter Bunny installation.
While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable!
Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example:
............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............
The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them.
So, for these two antennas with frequency a, they create the two antinodes marked with #:
..........
...#......
..........
....a.....
..........
.....a....
..........
......#...
..........
..........
Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......#...
..........
..........
Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......A...
..........
..........
The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna:
......#....#
...#....0...
....#0....#.
..#....0....
....0....#..
.#....A.....
...#........
#......#....
........A...
.........A..
..........#.
..........#.
Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map.
Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?
Your puzzle answer was 332.
--- Part Two ---
Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations.
Whoops!
After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency).
So, these three T-frequency antennas now create many antinodes:
T....#....
...T......
.T....#...
.........#
..#.......
..........
...#......
..........
....#.....
..........
In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9.
The original example now has 34 antinodes, including the antinodes that appear on every antenna:
##....#....#
.#.#....0...
..#.#0....#.
..##...0....
....0....#..
.#...#A....#
...#..#.....
#....#.#....
..#.....A...
....#....A..
.#........#.
...#......##
Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode? | 1174 | const fs = require('fs');
// Load and parse the input file into a grid
const loadGrid = () => {
return fs.readFileSync('input.txt', 'utf8')
.trim()
.split('\n')
.map(line => line.split(''));
};
// Compute the greatest common divisor (GCD) of two numbers
const calculateGCD = (a, b) => {
while (b !== 0) {
[a, b] = [b, a % b];
}
return a;
};
// Find all unique antinode positions in the grid
const calculateAntinodes = (grid) => {
const rows = grid.length;
const cols = grid[0].length;
const antinodes = new Set();
// Iterate through all pairs of antennas
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const frequency = grid[i][j];
if (frequency === '.') continue; // Skip empty spaces
for (let k = 0; k < rows; k++) {
for (let l = 0; l < cols; l++) {
if (grid[k][l] !== frequency || (i === k && j === l)) continue; // Skip same antenna or different frequencies
// Calculate the direction vector between the two antennas
const dx = k - i;
const dy = l - j;
const gcd = calculateGCD(Math.abs(dx), Math.abs(dy));
const stepX = dx / gcd;
const stepY = dy / gcd;
// Traverse in the direction of the vector to find antinodes
let x = i + stepX;
let y = j + stepY;
while (x >= 0 && x < rows && y >= 0 && y < cols) {
antinodes.add(`${x},${y}`);
x += stepX;
y += stepY;
}
// Traverse in the opposite direction to find antinodes
x = i - stepX;
y = j - stepY;
while (x >= 0 && x < rows && y >= 0 && y < cols) {
antinodes.add(`${x},${y}`);
x -= stepX;
y -= stepY;
}
}
}
}
}
return antinodes.size;
};
// Main function to execute the solution
const main = () => {
const grid = loadGrid();
const antinodeCount = calculateAntinodes(grid);
console.log(antinodeCount);
};
// Run the main function
main(); | javascript |
2024 | 8 | 2 | --- Day 8: Resonant Collinearity ---
You find yourselves on the roof of a top-secret Easter Bunny installation.
While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable!
Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example:
............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............
The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them.
So, for these two antennas with frequency a, they create the two antinodes marked with #:
..........
...#......
..........
....a.....
..........
.....a....
..........
......#...
..........
..........
Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......#...
..........
..........
Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location:
..........
...#......
#.........
....a.....
........a.
.....a....
..#.......
......A...
..........
..........
The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna:
......#....#
...#....0...
....#0....#.
..#....0....
....0....#..
.#....A.....
...#........
#......#....
........A...
.........A..
..........#.
..........#.
Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map.
Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?
Your puzzle answer was 332.
--- Part Two ---
Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations.
Whoops!
After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency).
So, these three T-frequency antennas now create many antinodes:
T....#....
...T......
.T....#...
.........#
..#.......
..........
...#......
..........
....#.....
..........
In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9.
The original example now has 34 antinodes, including the antinodes that appear on every antenna:
##....#....#
.#.#....0...
..#.#0....#.
..##...0....
....0....#..
.#...#A....#
...#..#.....
#....#.#....
..#.....A...
....#....A..
.#........#.
...#......##
Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode? | 1174 | const fs = require('fs');
const input = fs.readFileSync('input.txt', 'utf8').trim();
const lines = input.split('\n');
const height = lines.length;
const width = lines[0].length;
const antennas = {};
// Collect antennas by frequency
for (let y = 0; y < height; y++) {
const line = lines[y];
for (let x = 0; x < width; x++) {
const char = line[x];
if (/[a-zA-Z0-9]/.test(char)) {
if (!antennas[char]) antennas[char] = [];
antennas[char].push({ x, y });
}
}
}
const antinodes = new Set();
function gcd(a, b) {
while (b !== 0) {
[a, b] = [b, a % b];
}
return Math.abs(a);
}
for (const freq in antennas) {
const positions = antennas[freq];
const n = positions.length;
for (let i = 0; i < n; i++) {
const A = positions[i];
for (let j = i + 1; j < n; j++) {
const B = positions[j];
let dx = B.x - A.x;
let dy = B.y - A.y;
const stepGCD = gcd(dx, dy);
dx /= stepGCD;
dy /= stepGCD;
// Include positions along the line in both directions
const points = [];
// From A towards B
let x = A.x;
let y = A.y;
while (x >= 0 && x < width && y >= 0 && y < height) {
const key = `${x},${y}`;
antinodes.add(key);
x += dx;
y += dy;
}
// From A in the opposite direction
x = A.x - dx;
y = A.y - dy;
while (x >= 0 && x < width && y >= 0 && y < height) {
const key = `${x},${y}`;
antinodes.add(key);
x -= dx;
y -= dy;
}
}
}
}
console.log(antinodes.size); | javascript |
2024 | 9 | 1 | --- Day 9: Disk Fragmenter ---
Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls.
While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help.
He shows you the disk map (your puzzle input) he's already generated. For example:
2333133121414131402
The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space.
So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them).
Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks:
0..111....22222
The first example above, 2333133121414131402, represents these individual blocks:
00...111...2...333.44.5555.6666.777.888899
The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this:
0..111....22222
02.111....2222.
022111....222..
0221112...22...
02211122..2....
022111222......
The first example requires a few more steps:
00...111...2...333.44.5555.6666.777.888899
009..111...2...333.44.5555.6666.777.88889.
0099.111...2...333.44.5555.6666.777.8888..
00998111...2...333.44.5555.6666.777.888...
009981118..2...333.44.5555.6666.777.88....
0099811188.2...333.44.5555.6666.777.8.....
009981118882...333.44.5555.6666.777.......
0099811188827..333.44.5555.6666.77........
00998111888277.333.44.5555.6666.7.........
009981118882777333.44.5555.6666...........
009981118882777333644.5555.666............
00998111888277733364465555.66.............
0099811188827773336446555566..............
The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead.
Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928.
Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) | 6421128769094 | const fs = require('fs');
// Load the disk map from the input file
const loadDiskMap = (filePath) => {
return fs.readFileSync(filePath, 'utf8').trim();
};
// Parse the disk map into a list of blocks
const parseDiskMap = (diskMap) => {
const blocks = [];
let isFile = true;
let fileId = 0;
for (const char of diskMap) {
const length = parseInt(char, 10);
if (isFile) {
// Add file blocks with the current file ID
for (let i = 0; i < length; i++) {
blocks.push(fileId);
}
fileId++;
} else {
// Add free space blocks represented by -1
for (let i = 0; i < length; i++) {
blocks.push(-1);
}
}
// Alternate between file and free space
isFile = !isFile;
}
return blocks;
};
// Compact the disk by moving file blocks to the leftmost free space
const compactDisk = (blocks) => {
while (true) {
const leftmostFreeIndex = blocks.indexOf(-1);
if (leftmostFreeIndex === -1) break; // No free space left
let lastFileIndex = blocks.length - 1;
while (lastFileIndex > leftmostFreeIndex && blocks[lastFileIndex] === -1) {
lastFileIndex--;
}
if (lastFileIndex <= leftmostFreeIndex) break; // No file blocks to move
// Move the last file block to the leftmost free space
blocks[leftmostFreeIndex] = blocks[lastFileIndex];
blocks[lastFileIndex] = -1;
}
return blocks;
};
// Calculate the filesystem checksum
const calculateChecksum = (blocks) => {
return blocks.reduce((sum, block, index) => {
return block !== -1 ? sum + index * block : sum;
}, 0);
};
// Main function to execute the solution
const main = () => {
const diskMap = loadDiskMap('input.txt');
const blocks = parseDiskMap(diskMap);
const compactedBlocks = compactDisk(blocks);
const checksum = calculateChecksum(compactedBlocks);
console.log(checksum);
};
// Run the program
main(); | javascript |
2024 | 9 | 1 | --- Day 9: Disk Fragmenter ---
Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls.
While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help.
He shows you the disk map (your puzzle input) he's already generated. For example:
2333133121414131402
The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space.
So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them).
Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks:
0..111....22222
The first example above, 2333133121414131402, represents these individual blocks:
00...111...2...333.44.5555.6666.777.888899
The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this:
0..111....22222
02.111....2222.
022111....222..
0221112...22...
02211122..2....
022111222......
The first example requires a few more steps:
00...111...2...333.44.5555.6666.777.888899
009..111...2...333.44.5555.6666.777.88889.
0099.111...2...333.44.5555.6666.777.8888..
00998111...2...333.44.5555.6666.777.888...
009981118..2...333.44.5555.6666.777.88....
0099811188.2...333.44.5555.6666.777.8.....
009981118882...333.44.5555.6666.777.......
0099811188827..333.44.5555.6666.77........
00998111888277.333.44.5555.6666.7.........
009981118882777333.44.5555.6666...........
009981118882777333644.5555.666............
00998111888277733364465555.66.............
0099811188827773336446555566..............
The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead.
Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928.
Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) | 6421128769094 | const fs = require('fs');
// Helper function to parse the input disk map into an array of file lengths and free space lengths
const parseDiskMap = (input) => {
const diskLengths = input.split('').map(Number);
let disk = [];
let fileId = 0;
let isFile = true;
// Build the initial disk representation by alternating between file blocks and free space blocks
diskLengths.forEach((length) => {
if (isFile) {
// Add file blocks
disk.push(...Array(length).fill(fileId));
fileId++;
} else {
// Add free space blocks represented by -1
disk.push(...Array(length).fill(-1));
}
isFile = !isFile; // Toggle between file and free space
});
return disk;
};
// Helper function to simulate the compaction of files on the disk
const compactDisk = (disk) => {
let moved = true;
while (moved) {
moved = false;
// Find the leftmost free space index
let leftmostFreeIndex = disk.indexOf(-1);
if (leftmostFreeIndex === -1) {
// No free space left, disk is compacted
break;
}
// Find the last file block index
let lastFileIndex = disk.length - 1;
while (lastFileIndex > leftmostFreeIndex && disk[lastFileIndex] === -1) {
lastFileIndex--;
}
if (lastFileIndex <= leftmostFreeIndex) {
// No file blocks to move
break;
}
// Move the last file block to the leftmost free space
disk[leftmostFreeIndex] = disk[lastFileIndex];
disk[lastFileIndex] = -1;
// Set moved flag to true to keep going
moved = true;
}
return disk;
};
// Helper function to calculate the checksum of the compacted disk
const calculateChecksum = (disk) => {
return disk.reduce((checksum, block, index) => {
if (block !== -1) {
checksum += index * block; // Sum the product of position and file ID
}
return checksum;
}, 0);
};
// Main function to orchestrate the solution
const calculateDiskChecksum = (filePath) => {
const input = fs.readFileSync(filePath, 'utf-8').trim();
// Step 1: Parse the disk map into the initial disk representation
let disk = parseDiskMap(input);
// Step 2: Compact the disk by moving file blocks to the leftmost free space
disk = compactDisk(disk);
// Step 3: Calculate and return the checksum
return calculateChecksum(disk);
};
// Output the resulting checksum
const checksum = calculateDiskChecksum('input.txt');
console.log(checksum); | javascript |
2024 | 9 | 1 | --- Day 9: Disk Fragmenter ---
Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls.
While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help.
He shows you the disk map (your puzzle input) he's already generated. For example:
2333133121414131402
The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space.
So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them).
Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks:
0..111....22222
The first example above, 2333133121414131402, represents these individual blocks:
00...111...2...333.44.5555.6666.777.888899
The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this:
0..111....22222
02.111....2222.
022111....222..
0221112...22...
02211122..2....
022111222......
The first example requires a few more steps:
00...111...2...333.44.5555.6666.777.888899
009..111...2...333.44.5555.6666.777.88889.
0099.111...2...333.44.5555.6666.777.8888..
00998111...2...333.44.5555.6666.777.888...
009981118..2...333.44.5555.6666.777.88....
0099811188.2...333.44.5555.6666.777.8.....
009981118882...333.44.5555.6666.777.......
0099811188827..333.44.5555.6666.77........
00998111888277.333.44.5555.6666.7.........
009981118882777333.44.5555.6666...........
009981118882777333644.5555.666............
00998111888277733364465555.66.............
0099811188827773336446555566..............
The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead.
Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928.
Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) | 6421128769094 | const fs = require('fs');
// Read and parse the input from the file
const getInput = (filePath) => {
const input = fs.readFileSync(filePath, 'utf-8').trim();
return input.split('').map(Number); // Convert the input to an array of numbers
};
// Build the initial disk state (alternating files and free spaces)
const buildDiskState = (diskLengths) => {
let disk = [];
let fileId = 0;
let isFile = true;
for (let length of diskLengths) {
if (isFile) {
disk.push(...Array(length).fill(fileId)); // Add file blocks
fileId++;
} else {
disk.push(...Array(length).fill(-1)); // Add free space blocks
}
isFile = !isFile; // Toggle between file and free space
}
return disk;
};
// Compact the disk by moving file blocks to the leftmost available free space
const compactDisk = (disk) => {
let moved = true;
while (moved) {
moved = false;
const leftmostFreeIndex = disk.indexOf(-1);
if (leftmostFreeIndex === -1) break; // No free space left to move files into
// Find the last file block's index
let lastFileIndex = disk.length - 1;
while (lastFileIndex > leftmostFreeIndex && disk[lastFileIndex] === -1) {
lastFileIndex--;
}
// If no file blocks to move, stop the process
if (lastFileIndex <= leftmostFreeIndex) break;
// Move the last file block to the leftmost free space
disk[leftmostFreeIndex] = disk[lastFileIndex];
disk[lastFileIndex] = -1; // Mark the last file block position as free
moved = true; // Continue compacting
}
return disk;
};
// Calculate the checksum by summing the product of positions and file IDs
const calculateChecksum = (disk) => {
return disk.reduce((checksum, fileId, index) => {
if (fileId !== -1) {
checksum += index * fileId; // Multiply position by file ID and sum
}
return checksum;
}, 0);
};
// Main function to orchestrate the disk processing and checksum calculation
const processDisk = (filePath) => {
const diskLengths = getInput(filePath); // Step 1: Get and parse the disk map
let disk = buildDiskState(diskLengths); // Step 2: Build the initial disk state
disk = compactDisk(disk); // Step 3: Compact the disk to remove free space
const checksum = calculateChecksum(disk); // Step 4: Calculate the checksum
return checksum;
};
// Run the function and print the resulting checksum
const checksum = processDisk('input.txt');
console.log(checksum); | javascript |
2024 | 9 | 1 | --- Day 9: Disk Fragmenter ---
Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls.
While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help.
He shows you the disk map (your puzzle input) he's already generated. For example:
2333133121414131402
The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space.
So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them).
Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks:
0..111....22222
The first example above, 2333133121414131402, represents these individual blocks:
00...111...2...333.44.5555.6666.777.888899
The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this:
0..111....22222
02.111....2222.
022111....222..
0221112...22...
02211122..2....
022111222......
The first example requires a few more steps:
00...111...2...333.44.5555.6666.777.888899
009..111...2...333.44.5555.6666.777.88889.
0099.111...2...333.44.5555.6666.777.8888..
00998111...2...333.44.5555.6666.777.888...
009981118..2...333.44.5555.6666.777.88....
0099811188.2...333.44.5555.6666.777.8.....
009981118882...333.44.5555.6666.777.......
0099811188827..333.44.5555.6666.77........
00998111888277.333.44.5555.6666.7.........
009981118882777333.44.5555.6666...........
009981118882777333644.5555.666............
00998111888277733364465555.66.............
0099811188827773336446555566..............
The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead.
Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928.
Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) | 6421128769094 | const fs = require('fs');
// Load the disk map from the input file
const loadInput = (filePath) => fs.readFileSync(filePath, 'utf8').trim();
// Parse the disk map into blocks
const parseBlocks = (diskMap) => {
const blocks = [];
let isFile = true;
let fileId = 0;
for (const char of diskMap) {
const length = parseInt(char, 10);
if (isFile) {
for (let i = 0; i < length; i++) blocks.push(fileId);
fileId++;
} else {
for (let i = 0; i < length; i++) blocks.push(-1);
}
isFile = !isFile;
}
return blocks;
};
// Compact the disk by moving file blocks to the leftmost free space
const compactBlocks = (blocks) => {
while (true) {
const freeIndex = blocks.indexOf(-1);
if (freeIndex === -1) break;
let lastFileIndex = blocks.length - 1;
while (lastFileIndex > freeIndex && blocks[lastFileIndex] === -1) lastFileIndex--;
if (lastFileIndex <= freeIndex) break;
blocks[freeIndex] = blocks[lastFileIndex];
blocks[lastFileIndex] = -1;
}
return blocks;
};
// Calculate the checksum of the compacted disk
const computeChecksum = (blocks) => {
return blocks.reduce((sum, block, index) => (block !== -1 ? sum + index * block : sum), 0);
};
// Main function to execute the solution
const main = () => {
const diskMap = loadInput('input.txt');
const blocks = parseBlocks(diskMap);
const compactedBlocks = compactBlocks(blocks);
const checksum = computeChecksum(compactedBlocks);
console.log(checksum);
};
// Run the program
main(); | javascript |
2024 | 9 | 1 | --- Day 9: Disk Fragmenter ---
Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls.
While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help.
He shows you the disk map (your puzzle input) he's already generated. For example:
2333133121414131402
The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space.
So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them).
Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks:
0..111....22222
The first example above, 2333133121414131402, represents these individual blocks:
00...111...2...333.44.5555.6666.777.888899
The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this:
0..111....22222
02.111....2222.
022111....222..
0221112...22...
02211122..2....
022111222......
The first example requires a few more steps:
00...111...2...333.44.5555.6666.777.888899
009..111...2...333.44.5555.6666.777.88889.
0099.111...2...333.44.5555.6666.777.8888..
00998111...2...333.44.5555.6666.777.888...
009981118..2...333.44.5555.6666.777.88....
0099811188.2...333.44.5555.6666.777.8.....
009981118882...333.44.5555.6666.777.......
0099811188827..333.44.5555.6666.77........
00998111888277.333.44.5555.6666.7.........
009981118882777333.44.5555.6666...........
009981118882777333644.5555.666............
00998111888277733364465555.66.............
0099811188827773336446555566..............
The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead.
Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928.
Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) | 6421128769094 | // Read the input disk map as a string
const fs = require('fs');
const input = fs.readFileSync('input.txt', 'utf-8').trim();
// Parse the disk map into file lengths and free space lengths
const diskLengths = input.split('').map(Number);
let disk = [];
let fileId = 0;
let isFile = true;
// Build the initial disk representation
for (let i = 0; i < diskLengths.length; i++) {
const length = diskLengths[i];
if (isFile) {
// Add blocks for the current file with the file ID
for (let j = 0; j < length; j++) {
disk.push(fileId);
}
fileId++;
} else {
// Add free space blocks represented by -1
for (let j = 0; j < length; j++) {
disk.push(-1);
}
}
// Alternate between file and free space
isFile = !isFile;
}
// Simulate moving file blocks one at a time from the end to the leftmost free space
while (true) {
// Find the leftmost free space index
let leftmostFreeIndex = disk.indexOf(-1);
if (leftmostFreeIndex === -1) {
// No free space left, disk is compacted
break;
}
// Find the last file block index
let lastFileIndex = disk.length - 1;
while (lastFileIndex > leftmostFreeIndex && disk[lastFileIndex] === -1) {
lastFileIndex--;
}
if (lastFileIndex <= leftmostFreeIndex) {
// No file blocks to move
break;
}
// Move the last file block to the leftmost free space
disk[leftmostFreeIndex] = disk[lastFileIndex];
disk[lastFileIndex] = -1;
}
// Calculate the filesystem checksum
let checksum = 0;
for (let i = 0; i < disk.length; i++) {
if (disk[i] !== -1) {
// Sum the product of position and file ID
checksum += i * disk[i];
}
}
// Output the resulting checksum
console.log(checksum); | javascript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.