Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. void Graph::calculateNeighbors()
  2.     {
  3.         unsigned short numberOfNeighbors = NUMBER_OF_NEIGHBORS < numberOfNodes ? NUMBER_OF_NEIGHBORS : numberOfNodes;
  4.         neighbors = std::vector< std::vector<unsigned short> >(numberOfNodes);
  5.  
  6.         for(unsigned int i = 0; i < numberOfNodes; ++i)
  7.         {
  8.             for(unsigned int j = 0; j < numberOfNodes; ++j)
  9.             {
  10.                 if(i == j) //It should not be neighbor with it self
  11.                     continue;
  12.  
  13.                 unsigned int dist = getDistance(i,j); //Distance between this node and another
  14.  
  15.                 //If the neighbor list is not yet filled just insert it where it should be
  16.                 if(neighbors[i].size() < numberOfNeighbors)
  17.                 {
  18.                     bool found_place = false;
  19.                     //Insertion in correct position
  20.                     for(unsigned int k = 0; k < neighbors[i].size(); ++k)
  21.                     {
  22.                         //We found a place where the city is futher away than this
  23.                         if(dist < getDistance(i,neighbors[i][k]))
  24.                         {
  25.                             neighbors[i].insert(neighbors[i].begin() + k, j);
  26.                             found_place = true;
  27.                             break;
  28.                         }
  29.                     }
  30.                     //If the list only contains closer cities it should be in the end
  31.                     if(!found_place)
  32.                         neighbors[i].push_back(j);
  33.                 }
  34.                 else if(dist < getDistance(i, neighbors[i].back()))//The neighbor list is filled check if the last is futher away
  35.                 {
  36.                     //Search backwards to find where to place it
  37.                     for(unsigned int k = neighbors[i].size() -1 ; k >= 0; --k)
  38.                     {
  39.                         //We found a place where the city is futher away than this
  40.                         if(dist < getDistance(i,neighbors[i][k]))
  41.                         {
  42.                             neighbors[i].insert(neighbors[i].begin() + k, j);
  43.                             //The list now contains one element to much so remove the last
  44.                             neighbors[i].pop_back();
  45.                             break;
  46.                         }
  47.                     }
  48.                 }
  49.             }
  50.  
  51.         }
  52.         return;
  53.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement