### Create an Account

Home / Questions / Task 1.1: Randomly generate initial population of strings - We are going to write a function...

# Task 1.1: Randomly generate initial population of strings - We are going to write a function...

Task 1.1: Randomly generate initial population of strings
We are going to write a function buildPopulation that will initialize 200 random strings (all the same
length as the target phrase) containing upper/lowercase letters and spaces. You should store these population members in a single string array, which your function should output. In this function, you should also
define the population size as a variable, an important quantity that we will come back to often in this
project.
To generate random characters, we simply have to generate integers which correspond to text characters in
Following the biology analogy, our population (string array) now contains organisms (strings) with DNA
bits (individual characters) that were randomly generated. We are going to try and match that DNA to the
target pnhrase’s DNA.
Task 1.2: Calculate the fitness of each member in the population
In this example, we will simply define fitness as how many characters the current member of the population
has correct when compared to our target phrase. For example, if our target phrase is ‘Hello World’, and we
are assessing the fitness of the string ‘qK lfdRoPLd’, we would compare it as follows:
Target: H e l l o W o r l d
Test string: q k l f d R o P L d
DNA match: 0 0 0 1 0 0 0 1 0 0 1
The test string would have a fitness score of 3, due to having 3 DNA matches to the target phrase. A phrase
with 100% fitness (i.e., the phrase ‘Hello World’) would have a fitness score of 11 in this example.
You can see that with a longer target string, the maximum possible fitness goes up. Furthermore, having a
fitness of 3 in a phrase like ‘Hello World’ is much less significant to having a fitness of 3 in a shorter phrase
like ‘Hello’. Therefore, it is going to be more useful for us to look at the string’s fitness as a percentage,
where 0 has no matches, and 1 is completely matching (also known as normalizing the fitness score). In
this case the test string has a fitness of approximately 0.273, or 27.3%.
We will now write a function calculateFitness which calculates the fitness of the entire population in the
manner discussed above.

Attachments:

Apr 09 2020 View more View Less