Untitled
unknown
c_cpp
a year ago
1.3 kB
2
Indexable
Never
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; double eval(int *pj); int* RandomSolutionGenerator(){ int* solution = new int[100]; for(int i=0; i<100; i++){ solution[i] = rand() %2; } return solution; } double Evaluate(int* solution){ return eval(solution); } void Modify(int* solution){ int index = rand()%100; solution[index] = 1 - solution[index]; } void Modify(int* solution, double mutationRate){ for(int i=0; i<100; i++){ double randomVal = static_cast<double>(rand())/ RAND_MAX; if(randomVal < mutationRate){ solution[i] = 1- solution[i]; } } } void PrintSolution(int* solution){ for(int i=0; i<100; i++){ cout << solution[i]; } cout << endl; } int main() { srand(time(0)); int* solutionBase = RandomSolutionGenerator(); double fitnessBase = Evaluate(solutionBase); bool done = false; while(!done){ int* solutionNew = new int[100]; for(int i=0; i<100; i++){ solutionNew[i] = solutionBase[i]; } Modify(solutionNew, 0.01); double fitnessNew = Evaluate(solutionNew); cout << fitnessNew << endl; if(fitnessNew >= fitnessBase){ delete[] solutionBase; solutionBase = solutionNew; fitnessBase = fitnessNew; } if(fitnessNew >=100){ done = true; } } delete[] solutionBase; return 0; }