LeetKernels
ProblemsStart solving
Problems

14. Multi-Agent Simulation hard

Implement a program for a multi-agent flocking simulation (boids). The input consists of:

  • An array agents containing N agents, where N is the total number of agents
  • Each agent occupies 4 consecutive 32-bit floating point numbers in the array: [x,y,vx​,vy​], where:
    • (x,y) represents the agent's position in 2D space
    • (vx​,vy​) represents the agent's velocity vector
  • The total array size is 4 * N floats, with agent i's data stored at indices [4i, 4i+1, 4i+2, 4i+3]
  • Simulation Rules

    1. For each agent i, identify all neighbors j (where i=j) within radius r=5.0 using: (xi​−xj​)2+(yi​−yj​)2​<r
    2. Compute average velocity of neighboring agents: vavg​={∣Ni​∣1​∑j∈Ni​​vj​vi​​if ∣Ni​∣>0if ∣Ni​∣=0​ where Ni​ is the set of neighbors for agent i
    3. Update velocity: vnew​=v+α(vavg​−v), where α=0.05
    4. Update position: p​new​=p​+vnew​

    Implementation Requirements

    • Use only native features (external libraries are not permitted)
    • The solve function signature must remain unchanged
    • The final result must be stored in the agents_next array

    Example 1:

    Input: N = 2
    agents = [
      0.0, 0.0, 1.0, 0.0,    // Agent 0: [x, y, vx, vy]
      3.0, 4.0, 0.0, -1.0    // Agent 1: [x, y, vx, vy]
    ]
    
    Output:
    agents_next = [
      1.0, 0.0, 1.0, 0.0,    // Agent 0: [x, y, vx, vy]
      3.0, 3.0, 0.0, -1.0    // Agent 1: [x, y, vx, vy]
    ]
    

    Constraints

    • 1 ≤ N ≤ 100,000
    • Each agent's position and velocity components are 32-bit floats
    • Performance is measured with N = 10,000

    Starter code (CUDA)

    #include <cuda_runtime.h>
    
    // agents, agents_next are device pointers
    extern "C" void solve(const float* agents, float* agents_next, int N) {}
    

    Solve it on your GPU

    Previous: HistogrammingNext: Sorting

    From LeetGPU, CC BY-NC-ND 4.0.