InterviewDB Question

Battle Simulation - Simulate Turn-Based Combat and Determine Outcome

Question Details

Round 1 Coding

Problem

Simulate a turn-based battle between two armies. Each army has a list of units with attack and health values. Units attack in order; a defeated unit is removed. The first army to lose all units loses the battle.

python
def simulate_battle(
    army_a: list[tuple[int, int]],  # [(attack, health), ...]
    army_b: list[tuple[int, int]]
) -> str:  # "A", "B", or "DRAW"
    # Each round:
    #   Front unit of A attacks front unit of B (reduces health by A's attack)
    #   Front unit of B attacks front unit of A (simultaneous)
    #   Remove units with health <= 0
    # Continue until one or both armies are empty.
    ...

**Example**:
army_a = [(10, 20), (5, 15)]
army_b = [(8, 25)]

**Round 1** A[0](10 atk) vs B[0](8 atk)
  B[0].health = 25-10=15, A[0].health = 20-8=12

**Round 2** A[0] vs B[0]
  B[0].health = 15-10=5, A[0].health = 12-8=4

**Round 3** A[0] vs B[0]
  B[0].health = 5-10=-5 (dead), A[0].health = 4-8=-4 (dead)
  Both front units die simultaneously; A still has A[1]

simulate_battle(...) -> "A"

Follow-ups

  1. How do you handle the case where both front units die simultaneously?
  2. How would you add unit abilities (e.g. splash damage, healing)?
  3. How would you determine the optimal ordering of your own army to maximize win probability?
  4. What data structure best models the queues of units?

Full Details

Round 1 Coding

Problem

Simulate a turn-based battle between two armies. Each army has a list of units with attack and health values. Units attack in order; a defeated unit is removed. The first army to lose all units loses the battle.

python
def simulate_battle(
    army_a: list[tuple[int, int]],  # [(attack, health), ...]
    army_b: list[tuple[int, int]]
) -> str:  # "A", "B", or "DRAW"
    # Each round:
    #   Front unit of A attacks front unit of B (reduces health by A's attack)
    #   Front unit of B attacks front unit of A (simultaneous)
    #   Remove units with health <= 0
    # Continue until one or both armies are empty.
    ...

**Example**:
army_a = [(10, 20), (5, 15)]
army_b = [(8, 25)]

**Round 1** A[0](10 atk) vs B[0](8 atk)
  B[0].health = 25-10=15, A[0].health = 20-8=12

**Round 2** A[0] vs B[0]
  B[0].health = 15-10=5, A[0].health = 12-8=4

**Round 3** A[0] vs B[0]
  B[0].health = 5-10=-5 (dead), A[0].health = 4-8=-4 (dead)
  Both front units die simultaneously; A still has A[1]

simulate_battle(...) -> "A"

Follow-ups

  1. How do you handle the case where both front units die simultaneously?
  2. How would you add unit abilities (e.g. splash damage, healing)?
  3. How would you determine the optimal ordering of your own army to maximize win probability?
  4. What data structure best models the queues of units?
Free preview. Unlock all questions →

Topics

Coding Onsite Phone