data-structures · beginner · ~15 min

Manhattan distance between points

Declare a struct and access its members.

Challenge

Compute the Manhattan (grid) distance between two 2D points.

Task

Define struct Point { int x, y; }; and implement int manhattan(struct Point a, struct Point b) that returns the Manhattan distance |a.x - b.x| + |a.y - b.y|.

Input

Two struct Point values passed by value. Each has int fields x and y.

Output

The sum of the absolute differences of the coordinates, as an int.

Example

a={0,0}, b={3,4}   ->   7
a={5,5}, b={5,5}   ->   0

Edge cases

  • Identical points give 0.
  • Negative coordinates: take the absolute value of each difference.

Input format

Two struct Point values (each with int x, y), passed by value.

Output format

int: |a.x-b.x| + |a.y-b.y|.

Starter code

struct Point { int x, y; };

int manhattan(struct Point a, struct Point b) {
    /* TODO */
    return 0;
}

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