Categories
Programming

C++ Grids Distance

In city street grids, intersections are often defined by two integers, counting the position of horizontal and vertical streets (sometimes called streets and avenues). Imagine traveling from position (h1v1) to (h2v2). How many blocks do you traverse?

Even though there are many possible routes, the distance only depends on the differences h2 – h1 and v2 – v1. However, you need to take the absolute value because the differences might be negative.

Complete the following program that prints the number of blocks traveled, given the origin and destination of the trip (which will change as your code is tested).

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
   // Other values will be set during testing.
   // Your program needs to work with any coordinates.

   int h1 = 3; 
   int v1 = 4; 
   int h2 = 4; 
   int v2 = 4; 
   
   // Compute the distance between the two positions
   int distance = abs(h2 - h1);
   distance += abs(v2 - v1);
   cout << "Distance: " << distance << endl;

   return 0;
}