Skip to content

Instantly share code, notes, and snippets.

@rakslice
Created December 7, 2023 05:59
Show Gist options
  • Save rakslice/280680c61b2642ade481dfcdef0f4641 to your computer and use it in GitHub Desktop.
Save rakslice/280680c61b2642ade481dfcdef0f4641 to your computer and use it in GitHub Desktop.
AOC2023 Day 7
import collections
def contents(filename):
with open(filename, "r") as handle:
return handle.read()
def bin_cards(hand, part):
p = collections.Counter()
for ch in hand:
p[ch] += 1
j_count = p["J"]
if part == 2:
p["J"] = 0
by_count = []
for key, val in p.items():
by_count.append((val, key))
by_count.sort(reverse=True)
if part == 2:
a, b = by_count[0]
a += j_count
by_count[0] = (a, b)
return by_count
def find_type(by_count):
if by_count[0][0] == 5:
return 6
elif by_count[0][0] == 4:
return 5
elif by_count[0][0] == 3:
if by_count[1][0] == 2:
return 4
else:
return 3
elif by_count[0][0] == 2:
if by_count[1][0] == 2:
return 2
else:
return 1
else:
return 0
def problem(filename, part):
if part == 1:
cards_order = "A, K, Q, J, T, 9, 8, 7, 6, 5, 4, 3, 2".split(", ")
else:
cards_order = "A, K, Q, T, 9, 8, 7, 6, 5, 4, 3, 2, J".split(", ")
input = contents(filename).split("\n")
input = [x for x in input]
hands = []
cur = 0
for x in input:
hand, bid = x.split(None, 1)
bid = int(bid)
by_count = bin_cards(hand, part)
# print(by_count)
hand_type = find_type(by_count)
card_ranks = tuple([-cards_order.index(x) for x in hand])
entry = (hand_type, card_ranks, hand, bid)
hands.append(entry)
hands.sort()
for i, entry in enumerate(hands):
# print(entry)
hand_type, card_ranks, hand, bid = entry
rank = i + 1
cur += bid * rank
# print(cur)
return cur
def main():
day = 7
assert problem("test%02d.txt" % day, 1) == 6440
print(problem("input%02d.txt" % day, 1))
assert problem("test%02d.txt" % day, 2) == 5905
print(problem("input%02d.txt" % day, 2))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment