how to write greedy function?

here is what i got for my traveling salesmen problem. i seperate them in differnt parts.

this part check whether the salesmen pass the route more than once
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void TrackCity (Cities currentCity)
{
  int nCounter;
  list <Cities>::iterator it;
  bool bContinueRecursively;

  //register the current city in the stack
  beenThere.push_front(currentCity);

  for (nCounter = CITY_A; nCounter < NR_OF_CITIES; nCounter++)
  {
    if (vDistances[currentCity][nCouter] > 0)  //check valid distance
    {
      bContinueRecursively = true;  //the default is to go further...

      for (it = beenThere.begin(); it != beenThere.end(); it++)
        if (currentCity == *it)
          bContinueRecursively = false;  //...until proven wrong to do so

      if (bContinueRecursively == true)
      {
        TrackCity(nCouter);  //follow the white rabbit into a rabbit hole
                             //...which means going recursively to another city
      }
      else  //nowhere to go, so consider remembering the path
      {
        if (beenThere.size() > finalRouteResult.size())
          finalRouteResult = beenThere;
      }
    }
  }

  beenThere.pop_front();
}



this code is data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

struct Path {
  City destination;
  int distance;
};

struct City {
  vector<Path> neightbors;
  ... //other members (fields, methods, ...)

  void addPath(City dest, int dist) {
    Path path = { dest, dist };
    neightbors.push_back(path);
  }
};

int main() {
  City A, B, C;
  A.addPath(B, 1);
  A.addPath(C, 2);
  B.addPath(A, 1);
  B.addPath(C, 3);
  C.addPath(A, 2);
  C.addPath(B, 3);

  ... //do stuff with the cities


  return 0;
}


the next code is what i need help on.
1
2
3
4
5
6
7
8
9
10
11
12
13
14

if (parent1[0] != parent2[0])
	child[0] = 1;
	// You don't have a previous element for the first one.
	// Just decided on a value for child[0] where the parents' first element isn't the same.
else
	child[0] = parent1[0];

for (int i = 1; i < N; i++) { // N is the size of the arrays.
	if (parent1[i] == parent2[i])
		child[i] = parent1[i]; // You started well.
	else
		child[i] = greedyfunction(i);
}


So i think you kind of guess what i want to do, yes i am trying to code the genetic algorithm TSP,
anyways as you can see line 13 i called a function , but i don't know how to write the function. The use of the function is to complete the route by connecting the remaining city using the method (who's the nearest city). Can anyone give me some ideas?
??
Topic archived. No new replies allowed.