#include #include #include #include #include /** * @brief A simple Hill Climbing algorithm implementation. * Inspired by Chapter 1 of the "Building AI" course (Elements of AI). */ double objective_function(double x) { // A simple objective function: f(x) = - (x-3)^2 + 10 // Maximum at x = 3, f(3) = 10 return -std::pow(x - 3, 2) + 10; } int main() { std::cout << "--- Hill Climbing AI Component ---" << std::endl; // Random number generator std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> dis(0, 10); // Initial random state double current_x = dis(gen); double current_val = objective_function(current_x); double step_size = 0.1; std::cout << "Starting at x = " << current_x << ", f(x) = " << current_val << std::endl; for (int i = 0; i < 1000; ++i) { // Try moving left or right double next_x_plus = current_x + step_size; double next_x_minus = current_x - step_size; double val_plus = objective_function(next_x_plus); double val_minus = objective_function(next_x_minus); if (val_plus > current_val && val_plus >= val_minus) { current_x = next_x_plus; current_val = val_plus; } else if (val_minus > current_val && val_minus > val_plus) { current_x = next_x_minus; current_val = val_minus; } else { // No better neighbor found, peak reached (or local optimum) break; } } std::cout << "Final state: x = " << current_x << ", f(x) = " << current_val << std::endl; std::cout << "Peak found!" << std::endl; return 0; }