Skip to content

Instantly share code, notes, and snippets.

@jgrar
Created December 11, 2018 16:33
Show Gist options
  • Save jgrar/79dfa1e2df75ce2a713665c8d91d44b6 to your computer and use it in GitHub Desktop.
Save jgrar/79dfa1e2df75ce2a713665c8d91d44b6 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import sys
import re
class Node:
def __init__ (self, value):
self.value = value
self.next = None
self.prev = None
def __repr__ (self):
return repr(self.value)
class Ring:
def __init__ (self):
self.current = Node(0)
self.current.next = self.current
self.current.prev = self.current
def insert (self, node):
node.prev = self.current
node.next = self.current.next
self.current.next.prev = node
self.current.next = node
self.current = node
def seek (self, n):
if n < 0:
while n < 0:
self.current = self.current.prev
n += 1
else:
while 0 < n:
self.current = self.current.next
n -= 1
def pop (self):
value = self.current.value
self.current.prev.next = self.current.next
self.current.next.prev = self.current.prev
self.current = self.current.next
return value
def __repr__ (self):
outp = []
curr = self.current
while True:
outp.append(repr(curr))
curr = curr.next
if curr == self.current:
break
return repr(outp)
def play (nplayers, highest):
ring = Ring()
scores = {}
player = 0
for i in range(1, highest + 1):
if i % 23 == 0:
if player not in scores:
scores[player] = 0
ring.seek(-7)
scores[player] += i + ring.pop()
else:
ring.seek(1)
ring.insert(Node(i))
player = (player + 1) % nplayers
#print(ring, scores, scores[max(scores)])
return scores[max(scores)]
def parse (s):
specre = re.compile('(\d+) players; last marble is worth (\d+) points')
return map(int, specre.match(s).group(1, 2))
def main ():
nplayers, highest = parse(sys.stdin.read())
print(play(nplayers, highest))
if __name__ == '__main__':
assert(play(9, 25) == 32)
assert(play(10, 1618) == 8317)
assert(play(13, 7999) == 146373)
assert(play(17, 1104) == 2764)
assert(play(21, 6111) == 54718)
assert(play(30, 5807) == 37305)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment