Question

C++. Need some help getting started. We will also have the following two functions: 1. A...

C++. Need some help getting started.

We will also have the following two functions: 1. A mutate function that randomly modifies a chromosome. 2. A crossover function that takes two chromosomes and splits each one at the same spot, then combines them together. Our genetic algorithm works by iterating over generations of chromosomes via the following process: 1. Generate random population. 2. Until we get an answer that is good enough, do the next steps in a loop: (a) Do the following in a loop for twice as many times as our population size: i. Choose a chromosome from our population. With probability mr mutate the chromosome. ii. With probability cr, choose another random chromosome from our population and perform crossover. iii. Add the chromosome over to the new population. If we didn’t perform crossover or mutation this would copy over the chromosome from the previous generation. (b) Sort our new population by fitness. Keep the best half of it. (c) Replace our population by the new population. 3. Print out the best chromosome from the final population. Note that because our mutate function changes a chromosome at random and our crossover function simply combines existing chromosomes, none of the above process explicitly directs our program toward a solution. However, by random modification over a period of time keeping only the most fit chromosomes we can end up at an answer. 3 Our Genetic Algorithm For this exercise, we will implement a simple genetic algorithm. It will attempt to guess the content of a std::string passed as a command-line argument to our program. We will limit our strings to only lower-case letters. Note: if you want, you may include other printable characters, however the below description assumes you are using only lower-case letters. Our chromosomes will store a std::string as data. Mutation will randomly choose a character in the std::string and either increment or decrement it. Crossover will randomly choose an index and create a new string by taking the first part of one of the strings and concatenating it to the end of the other string. For example, suppose one of our chromosomes has the following data: abcdefg. A mutation might result in: abddefg or abcdeeg. Make sure that when mutating, we keep the result within the range for lower-case letters. For example, if the letter is a and we would decrement it, make it wrap to z. Similarly, if the letter is z and we would increment it, make it wrap to a. This makes sure our strings always have only lower-case letters in them. Suppose we have two chromosomes with the following data: one has abcdefg and the other has zyxwvut. A crossover would first randomly choose a position, say 4. This means we are splitting at position 4 so we take the first 4 characters of the first string: abcd and concatenate them with the last 3 characters of the second string: vut to create the new chromosome abcdvut. 2 We will assume that all strings have the same size in our implementation. We also have some target string that we are trying to guess. This is provided as argv[1] to our program. We can generate random chromosomes for our initial population by: Chromosome randomChromosome(int size) { std::ostringstream sout; for (int i = 0; i < size; i++) { sout << (char) ((rand() % 26) + 97); } return Chromosome(sout.str()); } where size is the length of our target string. Note that when we pick a random number, we first make sure it is in the range of [0, 26) then we shift it up by 97 because 97 is a in ASCII. This gives us a random lower-case letter. Our fitness function should return the sum of the differences between each character of the chromosome and the target. For example, given abcd and target string bbcd, the fitness function returns 1 because the first characters are 1 apart and the others are all the same. If we had abcd and target string bcde, our fitness function would return 4 because all four characters are 1 off from the target. Therefore, a fitness of 0 indicates a perfect match. Again, we assume all strings are the same size as the target. If you want to allow strings of different lengths, think about how you can change the fitness function so that it would give strings of the wrong length a poor fitness score. You must implement the mutate and crossover functions of the Chromosome class and the following function to run the algorithm: Chromosome runGA(std::string target, int popSize, double mr, double cr); where target is the target string, popSize is the size of the population we keep on each generation, mr is the mutation rate, and cr is the crossover rate. A main function has already been provided for testing purposes. It assumes the target string, pop size, mutation rate, and crossover rate have been passed as command-line arguments. The mutation rate and crossover rate values tell us how often we perform each operation. They will be in the range [0, 1] and act as probabilities. For example, suppose we have a mutation rate of 0.02 (that is, we mutate 2% of the time). To test if we should perform mutation on this chromosome we generate a random number in the range [0, 1] and check if the number we generated is <= the mutation rate. Because our number was generated at at random, it will fall in the range [0, 0.02] 2% of the time. When it does, we perform mutation. Apply the same logic for cr. Changing the population size will allow more chances for change per generation but make each generation take longer to compute.

#include "Chromosome.h"

Chromosome randomChromosome(int size)
{
std::ostringstream sout;
for (int i = 0; i < size; i++)
{
sout << (char) ((rand() % 26) + 97);
}
return Chromosome(sout.str());
}

Chromosome runGA(std::string target, int popSize, double mr, double cr)
{
// implement genetic algorithm here

// use a vector<Chromosome> for the population
// I recommend using STL algorithms such as std::sort

// remember, the GA is a loop until you find a chromosome
// of fitness 0

// on each iteration, you should be generating a new population
// of twice the size of popSize, filling it with chromosomes
// that have been mutated, crossed, and/or copied based on
// the probabilities given by mr and cr
// then sort it and keep only the best half as the population
// for the next iteration
// when you find a chromosome of fitness 0, you have finished and
// you should return it
}

int main(int argc, char **argv)
{
srand(time(0));
std::string target = argv[1];
int popSize = atoi(argv[2]);
double mr = atof(argv[3]);
double cr = atof(argv[4]);
Chromosome answer = runGA(target, popSize, mr, cr);

std::cout << "Solution found: " << answer << std::endl;
}

#ifndef CHROMOSOME_H
#define CHROMOSOME_H

#include <string>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>

class Chromosome
{
private:
std::string data;
public:
Chromosome(std::string d);

std::string getData() const;
Chromosome mutate() const;
Chromosome crossover(const Chromosome& other) const;
int fitness(const std::string& target) const;
};

std::ostream& operator<<(std::ostream& os, const Chromosome& c);

#endif

#include "Chromosome.h"

Chromosome::Chromosome(std::string d) : data(d)
{
}

std::string Chromosome::getData() const
{
return data;
}

Chromosome Chromosome::mutate() const
{
// implement mutation here

// your mutate function should randomly choose
// a character to modify then randomly choose
// to either increment or decrement it
// make sure to keep in range of lower-case letters!
}

Chromosome Chromosome::crossover(const Chromosome& c) const
{
// implement crossover here

// your crossover function should randomly choose
// an index in the range of the chromosomes
// then take the first part (up to the index) from *this
// and the last part (from index to end) from c and
// concatenate those together then return the result

  
}

int Chromosome::fitness(const std::string& target) const
{
// computes fitness by sum of differences of each character
// smaller is better (0 is perfect)

int diff = 0;
for (int i = 0; i < data.size(); i++)
{
int change = std::abs(data[i] - target[i]);
if (change > 13) // handles wrap around for letters
{
change = 26 - change;
}
diff += change;
}
return diff;
}

std::ostream& operator<<(std::ostream& os, const Chromosome& c)
{
os << c.getData();
return os;
}

0 0
Add a comment Improve this question Transcribed image text
Request Professional Answer

Request Answer!

We need at least 10 more requests to produce the answer.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the answer will be notified once they are available.
Know the answer?
Add Answer to:
C++. Need some help getting started. We will also have the following two functions: 1. A...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Similar Homework Help Questions
  • Can I get some help with this question for c++ if you can add some comments...

    Can I get some help with this question for c++ if you can add some comments too to help understand that will be much appreciated. Code: #include <cstdlib> #include <getopt.h> #include <iostream> #include <string> using namespace std; static long comparisons = 0; static long swaps = 0; void swap(int *a, int *b) {     // add code here } void selectionSort(int *first, int *last) {     // add code here } void insertionSort(int *first, int *last) {     // add code here }...

  • [3 Marks] t sluex h à local maximum in Simulated Annealing? (d) Assume we have the following fitn...

    Qd (V) required help [3 Marks] t sluex h à local maximum in Simulated Annealing? (d) Assume we have the following fitness function x'-60 * + 900 * x +100 f(x) Using a binary representation we can represent x using five binary digits. i. Given the following four chromosomes give the values for x and fx). Chromosome Binary String 11100 P2 10111 00100 [2 Marks] nts, apply one point crossover. Use a crossover point of 1 (where [3 Marks] ii....

  • HELP PLEASE ANSWER 3(c). Consider the following function object: #include <string> class CustomCompare public: bool operator...

    HELP PLEASE ANSWER 3(c). Consider the following function object: #include <string> class CustomCompare public: bool operator (const atd:istringk 1hs, const std::string& rhs) if (1hs. length) 0 && rhs.lengthO 0) return false; int 1 lhs. length )-1; intr rhs. length)-1; return (ro&&10) I Write one C++ statement that defines a variable myCustomPQ, where myCustomPQ is a priority queue storing strings and using CustomCompare.

  • Assignment 1 In this assignment you will be writing a tool to help you play the...

    Assignment 1 In this assignment you will be writing a tool to help you play the word puzzle game AlphaBear. In the game, certain letters must be used at each round or else they will turn into rocks! Therefore, we want to create a tool that you can provide with a list of letters you MUST use and a list of available letters and the program returns a list of all the words that contain required letters and only contain...

  • Hi, I have C++ programming problem here: Problem: Please modify your string type vector in for...

    Hi, I have C++ programming problem here: Problem: Please modify your string type vector in for push_back() function as below: void push_back(string str) { // increase vector size by one // initialize the new element with str } In addition, the standard library vector doesn't provide push_front(). Implement push_front() for your vector. Test your code with the main function below. int main() {    vector v1(3);    cout<<"v1: ";    v1.print(); // this should display -, -, -    for...

  • I need help in C++ implementing binary search tree. I have the .h file for the...

    I need help in C++ implementing binary search tree. I have the .h file for the binary search tree class. I have 4 classic texts, and 2 different dictionaries. Classic Texts: Alice In Wonderland.txt A Tale of Two Cities.txt Pride And Prejudice.txt War and Peace.txt 2 different dictionaries: Dictionary.txt Dictionary-brit.txt The data structures from the standard template library can not be used.The main program should open the text file, read in the words, remove the punctuation and change all the...

  • I need help modifying this program. How would I make sure that the methods is being...

    I need help modifying this program. How would I make sure that the methods is being called and checked in my main method? Here is what the program needs to run as: GDVEGTA GVCEKST The LCS has length 4 The LCS is GVET This is the error that I'm getting: The LCS has length 4 // I got this right The LCS is   //the backtrace is not being called for some reason c++ code: the cpp class: /** * calculate...

  • I need help implementing class string functions, any help would be appreciated, also any comments throughout...

    I need help implementing class string functions, any help would be appreciated, also any comments throughout would also be extremely helpful. Time.cpp file - #include "Time.h" #include <new> #include <string> #include <iostream> // The class name is Time. This defines a class for keeping time in hours, minutes, and AM/PM indicator. // You should create 3 private member variables for this class. An integer variable for the hours, // an integer variable for the minutes, and a char variable for...

  • I keep getting an error code in my C++ program. It says "[Error] 'strlen' was not...

    I keep getting an error code in my C++ program. It says "[Error] 'strlen' was not declared in this scope" in my main.cpp. Here are my codes. main.cpp #include <iostream> #include <string> #include "functions.h" using namespace std; //definition of the main function. //takes arguments from the command-line. int main(int argc, char *argv[]) { //Determine if you have enough arguments. //If not, output a usage message and exit program if (argc<2 || (argc == 2 && argv[1][0] == '-')) { //call...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT