tree
Creating an artificial intelligence (AI) application can range from simple algorithms, like decision trees or linear regression, to more complex systems like neural networks. Below is a straightforward example of a decision tree implemented in C++, which could be considered a rudimentary AI for classification purposes.
This decision tree will be very simple and will only work with categorical data. It will be hardcoded to classify whether a person is likely to go for a walk based on the weather and the temperature.
#include <iostream>
#include <string>
// Decision node struct
struct DecisionNode {
std::string question;
DecisionNode* yes;
DecisionNode* no;
DecisionNode(std::string q) : question(q), yes(nullptr), no(nullptr) {}
};
// Decision tree class
class DecisionTree {
private:
DecisionNode* root;
public:
DecisionTree() {
// Construct the decision tree
root = new DecisionNode("Is the weather nice?");
root->yes = new DecisionNode("Is it warm?");
root->no = new DecisionNode("false"); // false means will not go for a walk
root->yes->yes = new DecisionNode("true"); // true means will go for a walk
root->yes->no = new DecisionNode("false");
}
~DecisionTree() {
// Recursive delete
deleteTree(root);
}
void deleteTree(DecisionNode* node) {
if (node) {
deleteTree(node->yes);
deleteTree(node->no);
delete node;
}
}
// Classify method
std::string classify(const std::string& weather, const std::string& temperature) {
DecisionNode* node = root;
while (true) {
if (node->question == "true") return "Will go for a walk.";
if (node->question == "false") return "Will not go for a walk.";
if (node->question == "Is the weather nice?") {
node = (weather == "nice") ? node->yes : node->no;
} else if (node->question == "Is it warm?") {
node = (temperature == "warm") ? node->yes : node->no;
}
}
}
};
int main() {
DecisionTree tree;
std::string weather, temperature;
// Get user input
std::cout << "Is the weather nice? (nice/bad): ";
std::cin >> weather;
std::cout << "Is it warm? (warm/cold): ";
std::cin >> temperature;
// Classify and print the result
std::cout << tree.classify(weather, temperature) << std::endl;
return 0;
}
To compile this code, you need to save it to a file (say, decision_tree.cpp) and then use a C++ compiler:
g++ -o decision_tree decision_tree.cpp
./decision_tree
When you run the program, it will ask for the weather and temperature, and based on your answers, it will predict whether the person will go for a walk. This is a deterministic model and doesn't involve learning from data, but it is a starting point for building more complex AI systems that include learning capabilities.