Skip to content

Instantly share code, notes, and snippets.

@buckmaxwell
Created September 22, 2020 13:26
Show Gist options
  • Save buckmaxwell/7cc293c2cbdaff3ac4af6a6c21449545 to your computer and use it in GitHub Desktop.
Save buckmaxwell/7cc293c2cbdaff3ac4af6a6c21449545 to your computer and use it in GitHub Desktop.
2020.09.21 problem of the week
# Given an array of integers representing asteroids in a row, for each
# asteroid, the absolute value represents its size, and the sign represents its
# direction (positive = right, negative = left). Return the state of the
# asteroids after all collisions (assuming they are moving at the same speed).
# If two asteroids meet, the smaller one will explode. When they are the same
# size, they both explode. Asteroids moving in the same direction will never
# meet.
def asteroids(a):
# if there is to be a collision
for i in range(len(a)):
if len(a) >= i + 2 and a[i] >= 0 and a[i + 1] < 0:
# mutual destruction
if a[i] == abs(a[i + 1]):
return asteroids(a[:i] + a[i + 2 :])
# right moving asteroid wins
elif a[i] > abs(a[i + 1]):
return asteroids(a[: i + 1] + a[i + 2 :])
# left moving asteroid wins
else:
return asteroids(a[:i] + a[i + 1 :])
return a
assert asteroids([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, -11]) == [-11]
assert asteroids([10, 9, -11]) == [-11]
assert asteroids([10, -10]) == []
assert asteroids([5, 8, -5]) == [
5,
8,
] # The 8 and -5 collide, 8 wins. The 5 and 8 never collide.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment