#include #include using namespace std; #include"node.h" const double CONST_LIMIT = 10.0; void node::copy(node *source){ type = source->type; const_value = source->const_value; if(typebranches[i] != NULL){ branches[i] = new node; branches[i]->copy(source->branches[i]); } else{ branches[i] = NULL; } } } } void node::mutate(void){ if(rand()%100 < 1){ // 5% chance of mutating if(type < NUM_NON_TERMS){ // + or - type = rand() % NUM_NON_TERMS; } else{ type = NUM_NON_TERMS + rand()%NUM_TERMS; } if(type == 3){ // const const_value = const_value + (rand()%3 - 1); } } if(type < NUM_NON_TERMS){ branches[0]->mutate(); branches[1]->mutate(); } } void node::erase(void){ if(typeerase(); } delete this; } void node::full(int depth,int max,node *p){ /* creates full trees for the initial population */ parent = p; // point to parent node if(depth >= max) // if at max depth put in terminal type = NUM_NON_TERMS + rand()%NUM_TERMS; else{ // else add non-terminal type=rand()%NUM_NON_TERMS; switch (type){ case add: case subtract: for(int i =0; i < 2; i++){ branches[i] = new node; branches[i]->full(depth+1,max,this); } for(int i=2;i evaluate(X); r=branches[1] -> evaluate(X); return(l+r); case subtract: // - l=branches[0] -> evaluate(X); r=branches[1] -> evaluate(X); return(l-r); case inputX: // X return(X); case constt: return(const_value); default: cout << "Error, unknown instruction " << type << endl; } } /* Recursively counts terminal and non-terminals. */ void node::calc_size(int &terms, int &non_terms){ if(type >= NUM_NON_TERMS){ // count size terms++; return; } else{ non_terms++; for(int i=0;icalc_size(terms,non_terms); } } } }