data-structures · beginner · ~15 min

Dot product of 3-vectors

Aggregate over a typedef'd struct's fields.

Challenge

Compute the dot product of two 3D integer vectors.

Task

Define typedef struct { int x, y, z; } Vec3; and implement long dot(Vec3 a, Vec3 b) that returns a.x*b.x + a.y*b.y + a.z*b.z.

Input

Two Vec3 values passed by value. Each has int fields x, y, z.

Output

long: the sum of the element-wise products.

Example

a={1,2,3}, b={4,5,6}   ->   32
a={1,2,3}, b={0,0,0}   ->   0

Edge cases

  • A zero vector gives a dot product of 0.
  • Promote each product to long so large components do not overflow.

Input format

Two Vec3 values (each int x, y, z), passed by value.

Output format

long: a.x*b.x + a.y*b.y + a.z*b.z.

Constraints

Accumulate in long to avoid int overflow.

Starter code

typedef struct { int x, y, z; } Vec3;

long dot(Vec3 a, Vec3 b) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.