Is this Hill Climbing Algorithm code?

Hello, just wanted to know if the code below is considered hill climbing.

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
 calcCost (int ArrayOfCities[], const int NUM_CITIES) 
{
	int c = 0;
	for (int i = 0; i < NUM_CITIES; ++i)
	{
		for (int j = i + 1; j < NUM_CITIES; ++j)
		{
			if (ArrayOfCities[j] < ArrayOfCities[i])
			{
				c++;
			}
		}
	}
	return c;
}

void SwapElements (int ArrayOfCities[], int i, int j)
{
	int temp = ArrayOfCities[i];
	ArrayOfCities[i] = ArrayOfCities[j];
	ArrayOfCities[j] = temp;
}

int main()
{
	const int CITIES = 8;
	int iIndex = 1;
	int ArrayOfCities[CITIES];

	for (int i = 0; i < CITIES; ++i)
	{
		cout << "Enter distance for city " << iIndex << endl;
		cin >> ArrayOfCities[i];
		++iIndex;
	}

	int bestCost = calcCost(ArrayOfCities, CITIES);
	int iNewCost = 0, iSwaps = 0;
	while (bestCost > 0) 
	{
		for (int i = 0; i < CITIES - 1; ++i)
		{
			SwapElements(ArrayOfCities, i, i + 1);
			iNewCost = calcCost(ArrayOfCities, CITIES);
			if (bestCost > iNewCost)
			{
				++iSwaps;
				cout << "Performing Swap: " << iSwaps << endl;
				for (int i = 0; i < CITIES; ++i)
				{
					cout << ArrayOfCities[i] << "->";
				}

				cout << "\n";
				bestCost = iNewCost;
			}
			else
			{
				SwapElements(ArrayOfCities, i, i + 1);
			}
		}
	}
	
	cout << "\nFinal Route: \n";
	for (int i = 0; i < CITIES; i++)
	{
		cout << ArrayOfCities[i] << endl;
	}


Thanks!
This does look like a Hill Climbing algorithm to me but it doesn't look like a very good Hill Climbing algorithm. What you wrote is a "Greedy Hill Climbing" algorithm which isn't very good for two reasons:

1) It could get stuck in local maxima.
2) It doesn't always find the best (shortest) path. (I assume you're writing this to solve the salesperson problem)

I think you should look into Stochastic hill climbing instead of basic Hill Climbing if you want a more optimized Hill Climber that finds the shortest route and doesn't get stuck.

Try looking into Simulated Annealing (SA). It's a more optimized version and it is very easy to implement (it's about 10 lines of code total).

Reference: https://en.wikipedia.org/wiki/Simulated_annealing
Thank you Marine :) It's nice to see you're still around! :p

I tried to implement the SA but for some reason it couldn't find the shortest route, I'll give it another go.

Thank you again and nice MMA record! xD
Topic archived. No new replies allowed.