Upload hill_climbing.cpp with huggingface_hub
Browse files- hill_climbing.cpp +57 -0
hill_climbing.cpp
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <iostream>
|
| 2 |
+
#include <vector>
|
| 3 |
+
#include <cmath>
|
| 4 |
+
#include <algorithm>
|
| 5 |
+
#include <random>
|
| 6 |
+
|
| 7 |
+
/**
|
| 8 |
+
* @brief A simple Hill Climbing algorithm implementation.
|
| 9 |
+
* Inspired by Chapter 1 of the "Building AI" course (Elements of AI).
|
| 10 |
+
*/
|
| 11 |
+
|
| 12 |
+
double objective_function(double x) {
|
| 13 |
+
// A simple objective function: f(x) = - (x-3)^2 + 10
|
| 14 |
+
// Maximum at x = 3, f(3) = 10
|
| 15 |
+
return -std::pow(x - 3, 2) + 10;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
int main() {
|
| 19 |
+
std::cout << "--- Hill Climbing AI Component ---" << std::endl;
|
| 20 |
+
|
| 21 |
+
// Random number generator
|
| 22 |
+
std::random_device rd;
|
| 23 |
+
std::mt19937 gen(rd());
|
| 24 |
+
std::uniform_real_distribution<> dis(0, 10);
|
| 25 |
+
|
| 26 |
+
// Initial random state
|
| 27 |
+
double current_x = dis(gen);
|
| 28 |
+
double current_val = objective_function(current_x);
|
| 29 |
+
double step_size = 0.1;
|
| 30 |
+
|
| 31 |
+
std::cout << "Starting at x = " << current_x << ", f(x) = " << current_val << std::endl;
|
| 32 |
+
|
| 33 |
+
for (int i = 0; i < 1000; ++i) {
|
| 34 |
+
// Try moving left or right
|
| 35 |
+
double next_x_plus = current_x + step_size;
|
| 36 |
+
double next_x_minus = current_x - step_size;
|
| 37 |
+
|
| 38 |
+
double val_plus = objective_function(next_x_plus);
|
| 39 |
+
double val_minus = objective_function(next_x_minus);
|
| 40 |
+
|
| 41 |
+
if (val_plus > current_val && val_plus >= val_minus) {
|
| 42 |
+
current_x = next_x_plus;
|
| 43 |
+
current_val = val_plus;
|
| 44 |
+
} else if (val_minus > current_val && val_minus > val_plus) {
|
| 45 |
+
current_x = next_x_minus;
|
| 46 |
+
current_val = val_minus;
|
| 47 |
+
} else {
|
| 48 |
+
// No better neighbor found, peak reached (or local optimum)
|
| 49 |
+
break;
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
std::cout << "Final state: x = " << current_x << ", f(x) = " << current_val << std::endl;
|
| 54 |
+
std::cout << "Peak found!" << std::endl;
|
| 55 |
+
|
| 56 |
+
return 0;
|
| 57 |
+
}
|