File size: 1,726 Bytes
21770f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <random>

/**
 * @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;
}