Created
September 22, 2020 07:54
-
-
Save arkadyark/68c1601761794fbcfb875e1a580f80a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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. | |
Example: | |
$ asteroids([5, 8, -5]) -> [5, 8] // The 8 and -5 collide, 8 wins. The 5 and 8 never collide. | |
$ asteroids([10, -10]) -> [] // The 10 and -10 collide and they both explode. | |
Assumptions: | |
- No asteroids have 0 speed, so there are no 3 way collisions | |
- After colliding, the surviving asteroid doesn't keep colliding | |
''' | |
def asteroids(l): | |
survivors = [] | |
for i in range(len(l)): | |
size = abs(l[i]) | |
direction = int(l[i] / size) | |
if 0 <= i + direction < len(l): | |
neighbor_size = abs(l[i + direction]) | |
neighbor_direction = int(l[i + direction] / neighbor_size) | |
if neighbor_direction == direction or size > neighbor_size: | |
survivors.append(l[i]) | |
else: | |
survivors.append(l[i]) | |
return survivors | |
if __name__ == "__main__": | |
assert(asteroids([5, 8, -5]) == [5, 8]) | |
assert(asteroids([10, -10]) == []) | |
assert(asteroids([-10, -10]) == [-10, -10]) # No collision | |
assert(asteroids([1, -0.5]) == [1]) # Simple collision | |
assert(asteroids([-1, 1]) == [-1, 1]) # Diverge | |
print("All tests passed!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment