awelgorithms

Resolve opposing items with a stack

Updated

Collision problems (asteroids, surviving cars) scan items and use a stack of still-alive previous items. The new item may destroy the top, die, or both, depending on signs, directions, and strength.

What to focus on

Only the top can collide with the newcomer. Buried items wait. After resolving the top, the newcomer may still collide with the new top. That is pop-while.

Worked examples

right vs left

a = [5, 10, -5]
  1. -5 hits 10
  2. 10 wins
  3. 5 untouched

Result: [5, 10]

same direction

a = [5, 10]
  1. no oppose
  2. both live

Result: [5, 10]

empty

a = []
  1. nothing to collide

Result: []

Try it

Write collide(a). a is an array of non-zero integers. Positive means right, negative means left. Magnitude is abs(value). Scan left to right. Only the top fights the incoming item. Return the surviving stack bottom to top. a = [5, 10, -5] → [5, 10]. a = [5, 10] → [5, 10]. a = [] → [].

a is a list of non-zero integers and may be empty. Positive means right, negative means left. Magnitude is abs(value).