Question

For some reason I can't get the distance function to work. Could someone explain to me what I am doing wrong?

Main Function:

#include <iostream>
#include <cmath> 
using namespace std;

int distance(int**, int);

 int main()
 {
 int m;
 int goal [3][3] = { {1,2,3},{4,5,6},{7,8,0}};
 const int N = 3;
 int intial[N][N];
 cout << "Enter in values: \n";
 for(int i=0; i<3; i++)    //This loops on the rows.
{
    for(int j=0; j<3; j++) //This loops on the columns
    {
        cin >> intial[i][j];  
    }
}


 cout << goal[0][0] << "\n" ;
 m = distance(intial,N);
 system("PAUSE");
 return 0;
 }

Manhattan Distance calculation!

int distance(int** array,int N)
 {

  int MSum = 0;
  for (int x = 0; x < N; x++){ //Transversing rows(i)
      for (int y = 0; y < N; y++) { //traversing colums (j)
        int value = array[x][y]; // sets int to the value of space on board
            if (value != 0) { // Don't compute MD for element 0
               int targetX = (value - 1) / N; // expected x-coordinate (row)
               int targetY = (value - 1) % N; // expected y-coordinate (col)
               int dx = x - targetX; // x-distance to expected coordinate
               int dy = y - targetY; // y-distance to expected coordinate
               MSum += abs(dx) +abs(dy);   
            }
        }

  }
  int m = MSum;
  return m;

 }
Was it helpful?

Solution

This looks basically correct as far as logic goes. The array you pass in should be compatible with the function declaration and implementation. Here is a sample declaration:

int distance(int array[3][3],int N);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top