<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ evolution - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ evolution - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 13 Jun 2026 09:48:51 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/evolution/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Introduction to Evolutionary Game Theory ]]>
                </title>
                <description>
                    <![CDATA[ By Peter Gleeson For the longest time, the evolution of cooperative social behaviour has fascinated evolutionary biologists. The mathematical field of game theory helps shed light on how it emerges. Game theory is “the study of mathematical models of... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/introduction-to-evolutionary-game-theory/</link>
                <guid isPermaLink="false">66d460a8677cb8c6c15f3171</guid>
                
                    <category>
                        <![CDATA[ evolution ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Game Theory ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Math ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Science  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 13 Apr 2021 17:12:33 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/605de4899618b008528a7b69.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Peter Gleeson</p>
<p>For the longest time, the evolution of cooperative social behaviour has fascinated evolutionary biologists.</p>
<p>The mathematical field of game theory helps shed light on how it emerges. Game theory is “the study of mathematical models of strategic interaction among rational decision-makers” (according to <a target="_blank" href="https://en.wikipedia.org/wiki/Game_theory">Wikipedia</a>).</p>
<p>Game theory applies to “games” as varied as economics, politics, chess and tic-tac-toe. In each case, there are some rules, some “players” or “agents”, and a set of strategies available to them.</p>
<p>Each player has a concept of “utility” – a “currency” they seek to individually maximise through the strategies they play.</p>
<p>The currency of evolution is the concept of <a target="_blank" href="https://www.nature.com/scitable/blog/accumulating-glitches/the_meaning_of_fitness/">fitness</a>.</p>
<p>That is, the chance of being represented in the next generation. Genes and traits which increase the odds of survival to reproductive age are more likely to be passed on to future generations. Therefore, they confer a greater fitness to the individual which "hosts” them.</p>
<p>Evolutionary game theory takes the concepts from game theory and applies them in an evolutionary context.</p>
<p>For a given model, it lets you ask questions about which strategy prevails, and whether certain strategies can coexist. And if so – at what frequencies?</p>
<h2 id="heading-replicator-dynamics">Replicator dynamics</h2>
<p>Evolutionary game theory plays “games” over many generations.</p>
<p>Each game will alter the utility (that is, fitness) of the players. The next generation is produced, with players being represented proportionally to their overall fitness.</p>
<p>This set up is called “replicator dynamics”. It is easy to simulate and explore different models of evolutionary games.</p>
<p>The classic model of evolutionary game theory is the “Hawk-Dove” game, popularised by John Maynard Smith in the 1970s.</p>
<p>In this game, there exists a population of animals which compete for a finite resource (for example, food). The more resources an individual wins, the greater its fitness.</p>
<p>Each animal can play one of two strategies:</p>
<ul>
<li><strong>Hawks</strong> are aggressive, and will fight for a resource at all costs.</li>
<li><strong>Doves</strong> are passive, and will share instead of fight for a resource.</li>
</ul>
<p>The animals are all the same kind – “hawk” and “dove” refer to their behaviour.</p>
<p>There are three pairwise competitions that can exist:</p>
<p><strong>Hawk vs Hawk</strong></p>
<ul>
<li>If two hawks compete, they will engage in a 50:50 battle to win the resource. This is a winner-takes-all scenario – the winner obtains the full value of the resource. The injured loser pays a price, and loses a certain amount of fitness.</li>
</ul>
<p><strong>Hawk vs Dove</strong></p>
<ul>
<li>If a hawk meets a dove, the dove will back down immediately. The hawk wins the full value of the resource, and the dove walks (or, rather flies) away with nothing. But they do not pay any cost.</li>
</ul>
<p><strong>Dove vs Dove</strong></p>
<ul>
<li>When two doves meet, they agree to share the resource evenly. No one gets hurt.</li>
</ul>
<p>This can be modelled mathematically. Doing so allows us to understand whether these strategies can coexist (or if one of them prevails).</p>
<h3 id="heading-the-math-of-replicator-dynamics">The math of replicator dynamics</h3>
<p>Let <em>V</em> be the value of winning a contest, and <em>C</em> be the cost of injury in a contest.</p>
<p>Represent the frequency of hawks in the population as <em>p</em>, and the frequency of doves as <em>1-p</em>.</p>
<p>Now, define two functions F(H) and F(D) which define the expected fitness of playing the hawk and dove strategies, respectively.</p>
<p>Playing as a hawk will mean engaging in a hawk-vs-hawk contest with frequency <em>p.</em> The expected utility of doing so is understood as the average outcome. Half the time the hawk wins <em>V</em>, half the time it loses <em>C</em>.</p>
<p>The rest of a hawk’s contests will be against doves. This guarantees an easy win <em>V.</em></p>
<p><img src="https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F8b5ac2e8-fdfb-4ffc-8abe-15d0d014f580_544x112.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Playing as a dove will win nothing against hawks. But a dove will encounter another dove with frequency <em>1-p</em>. Under this scenario, the expected utility is the shared resource, worth <em>V/2</em>.</p>
<p><img src="https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F6303e0b2-d6ab-434d-b7ec-cad18a82d154_508x110.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now, set <em>F(H)</em> equal to <em>F(D)</em> and solve for <em>p</em>.</p>
<p>This reveals the frequency <em>p</em> at which the hawk strategy confers no more or less fitness than the dove strategy.</p>
<p>At this frequency, there is no advantage to either strategy, so this is the equilibrium at which both strategies may coexist.</p>
<p><img src="https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F77be89c1-0286-4673-867f-1c8e1a038cb7_516x104.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Some algebraic rearrangement gives:</p>
<p><img src="https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2Fca77237e-29a4-4826-af4a-2fbb390d3572_404x108.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Which provides the ratio of hawks-to-doves that exists at equilibrium.</p>
<p>Just a little more rearranging gives the equilibrium in terms of <em>p</em>:</p>
<p><img src="https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2Fb812b56c-8387-4a47-902e-61aaa87cf317_342x98.png" alt="Image" width="342" height="98" loading="lazy"></p>
<p>Considering the properties of this expression reveals two things:</p>
<ul>
<li>Whenever the cost <em>C</em> of losing a contest is less than or equal to the value <em>V</em> of winning, the hawk strategy will dominate. Neither strategy can coexist.</li>
<li>If the cost <em>C</em> is greater than the value <em>V</em>, the strategies will coexist in equilibrium.</li>
</ul>
<p>Plugging in the values <em>V</em>=4 and <em>C</em>=6 shows the equilibrium occurs when 2/3 of the population play the hawk strategy.</p>
<p>You can test this by simulating the model in Python.</p>
<h3 id="heading-the-code">The code</h3>
<p>In the file called bird.py:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> random

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bird</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, strategy</span>):</span>
        <span class="hljs-string">"""
        Each bird has a strategy type (hawk or dove)
        And a small starting fitness
        """</span>
        self.strategy = strategy
        self.fitness = <span class="hljs-number">10</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">contest</span>(<span class="hljs-params">self, opponent, v, c</span>):</span>
       <span class="hljs-string">"""
       Simulate the outcomes depending on the strategies
       """</span>

        <span class="hljs-comment"># both hawks --&gt; 50:50 battle</span>

        <span class="hljs-keyword">if</span> self.strategy == opponent.strategy == <span class="hljs-string">"hawk"</span>:
            <span class="hljs-keyword">if</span> random.randint(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>) == <span class="hljs-number">1</span>:
                self.fitness = self.fitness + v
                opponent.fitness = opponent.fitness - c
            <span class="hljs-keyword">else</span>:
                self.fitness = self.fitness - c
                opponent.fitness = opponent.fitness + v

        <span class="hljs-comment"># hawk meets dove</span>

        <span class="hljs-keyword">elif</span> self.strategy == <span class="hljs-string">"hawk"</span> != opponent.strategy:
            self.fitness = self.fitness + v
            opponent.fitness = opponent.fitness
        <span class="hljs-keyword">elif</span> self.strategy == <span class="hljs-string">"dove"</span> != opponent.strategy:
            self.fitness = self.fitness
            opponent.fitness = opponent.fitness + v

        <span class="hljs-comment"># both doves --&gt; share the resource</span>

        <span class="hljs-keyword">else</span>:
            self.fitness = self.fitness + v/<span class="hljs-number">2</span>
            opponent.fitness = opponent.fitness + v/<span class="hljs-number">2</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">spawn</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-string">"""
        Allow a small chance of mutation to flip strategy
        Otherwise, return offspring of the same type
        """</span>

        mutation = random.randint(<span class="hljs-number">0</span>, <span class="hljs-number">1000</span>) &gt; <span class="hljs-number">999</span>
        <span class="hljs-keyword">if</span> mutation:
            <span class="hljs-keyword">if</span> self.strategy == <span class="hljs-string">"dove"</span>:
                <span class="hljs-keyword">return</span> Bird(<span class="hljs-string">"hawk"</span>)
            <span class="hljs-keyword">else</span>:
                <span class="hljs-keyword">return</span> Bird(<span class="hljs-string">"dove"</span>)
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> Bird(self.strategy)
</code></pre>
<p>The next file is called simulation.py.</p>
<ol>
<li>Initialise a population of all doves.</li>
<li>Define a timestep function to simulate randomised contests.</li>
<li>Draw the next generation weighted by their relative fitnesses.</li>
<li>Rinse and repeat a thousand times over, then save the output as a graph.</li>
</ol>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> bird <span class="hljs-keyword">import</span> Bird
<span class="hljs-keyword">import</span> random
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
<span class="hljs-keyword">import</span> matplotlib


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">initialise</span>():</span>
    <span class="hljs-string">"""
    Create a population of birds - all dove to begin
    """</span>

    birds = []

    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(<span class="hljs-number">1000</span>):
        birds.append(Bird(<span class="hljs-string">"dove"</span>))

    <span class="hljs-keyword">return</span> (birds)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">timestep</span>(<span class="hljs-params">birds, value, cost</span>):</span>
    <span class="hljs-string">"""
    Pair up the birds, make them compete
    Then produce next generation, weighted by fitness
    """</span>

    next_generation = []

    random.shuffle(birds)

    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(<span class="hljs-number">1000</span>):

        <span class="hljs-comment"># pair up random birds to contest</span>
        a, b = random.sample(birds, <span class="hljs-number">2</span>)
        a.contest(b, value, cost)

    <span class="hljs-comment"># generate next generation</span>
    fitnesses = [bird.fitness <span class="hljs-keyword">for</span> bird <span class="hljs-keyword">in</span> birds]

    draw = random.choices(birds, k=<span class="hljs-number">1000</span>, weights=fitnesses)
    next_generation = [bird.spawn() <span class="hljs-keyword">for</span> bird <span class="hljs-keyword">in</span> draw]

    <span class="hljs-keyword">return</span> next_generation


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>

    birds = initialise()

    rows = []

    V = <span class="hljs-number">4</span> ; C = <span class="hljs-number">6</span>

    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(<span class="hljs-number">1000</span>):

        <span class="hljs-comment"># add the counts to a new row</span>
        strategy = [bird.strategy <span class="hljs-keyword">for</span> bird <span class="hljs-keyword">in</span> birds]
        n_hawks = strategy.count(<span class="hljs-string">"hawk"</span>)
        n_doves =  strategy.count(<span class="hljs-string">"dove"</span>)
        row = {<span class="hljs-string">'n_hawks'</span>: n_hawks, <span class="hljs-string">'n_doves'</span>: n_doves}
        rows.append(row)

        <span class="hljs-comment"># run the timestep function</span>
        birds = timestep(birds, V, C)


    <span class="hljs-comment"># create dataframe and save output</span>

    df = pd.DataFrame(rows)
    df.to_csv(<span class="hljs-string">'simulation.csv'</span>)
    fig = df.plot(y=[<span class="hljs-string">"n_hawks"</span>, <span class="hljs-string">"n_doves"</span>]).get_figure()
    fig.savefig(<span class="hljs-string">'simulation.pdf'</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    main()
</code></pre>
<p>And voilà - here’s an example of the output for <em>V</em>=4 and <em>C</em>=6:</p>
<p><img src="https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F44100a89-d377-435e-bf11-97b046db5f32_1438x1048.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Exactly as the theory predicts.</p>
<h2 id="heading-outro">Outro</h2>
<p>The evolution of complex systems is a fascinating field of study. Understanding how natural forces and competitive pressures can shape individual-level traits to give rise to complex social behaviours has been one of the major areas of research in biological sciences in the last few decades.</p>
<p>The ability of relatively simple mathematical models to accurately predict outcomes of dynamic systems is also a key point to take away. </p>
<p>In this case, it is the existence of a feedback loop that results in the two strategies reaching an equilibrium. The advantage conferred by either strategy varies depending on how many others in the population are playing that strategy.</p>
<p>In other words, when more individuals play "dove", there is an advantage to playing "hawk". However, as more individuals play "hawk", the expected value of playing "dove" increases.</p>
<p>Finally, the availability of programming and software tools makes it possible to test theoretical predictions through simulation.</p>
<p>If you found this article interesting, you may also find <a target="_blank" href="https://www.freecodecamp.org/news/how-to-model-an-epidemic-with-r/">How to Model an Epidemic With R</a> worth checking out, too.</p>
<p>You can follow more of my writing at <a target="_blank" href="https://gleeson.substack.com/">gleeson.substack.com</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Computer Science of Evolution: an Introduction to Genetic Algorithms ]]>
                </title>
                <description>
                    <![CDATA[ By Ben Mmari Being a computer scientist with an interest in evolution and biological processes, the topic of genetic algorithms, and more broadly, evolutionary computation is to me what a candy shop is to a 5-year-old: Heaven. The mere possibility of... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-computer-science-of-evolution-an-introduction-to-genetic-algorithms-b3871286c7e7/</link>
                <guid isPermaLink="false">66c36117c6c49ae59cf21ade</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ evolution ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Genetics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Science  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 11 Apr 2019 20:49:44 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*J3BtJTlHKnx3152UKoTgYg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ben Mmari</p>
<p>Being a computer scientist with an interest in evolution and biological processes, the topic of genetic algorithms, and more broadly, evolutionary computation is to me what a candy shop is to a 5-year-old: Heaven. The mere possibility of being able to merge two of my interests in such a seamless manner has been extremely exhilarating, and it would be wrong for me to keep this knowledge and excitement all to myself.</p>
<p>So in an attempt to test out some of my learnings thus far, and share my findings with the rest of the world, I have decided to put together a series of articles on this topic.</p>
<p>In this post, I will provide a brief introduction to genetic algorithms and explain how they imitate the same natural processes that have been taking place on Earth for billions of years.</p>
<h4 id="heading-life-on-earth"><strong>Life on Earth</strong></h4>
<p>Over the past 3.5 billion years, mother nature, father time, evolution and natural selection have collaborated together to produce <strong>all</strong> of the specialized forms of life that we see on earth today: like the carnivorous Venus Flytrap plant; the ocean-dwelling Atlantic Flying Fish; echolocation-using bats; long-necked giraffes; super-quick cheetahs, dancing Honeybees; and of course, yours truly, the street smart Homo sapiens.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/LmZm7DjfgyLwH3RpgYrQCnWCIj0L7xB9zYvG" alt="Image" width="224" height="225" loading="lazy">
<em>The Venus Flytrap is a carnivorous plant that primarily feasts on insects and arachnids.</em></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/tbRcMzxleAYOcEE8r-69ZP2n6lLGunkP4QYe" alt="Image" width="318" height="159" loading="lazy">
<em>Some bats use echolocation to navigate and hunt prey and contrary to popular belief, bats are actually not blind; a species of bats known as The Flying Foxes actually have better eyesight than humans.</em></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/9m1HytKWrGc6wd46E5ijI2zanCsYY8OWW1Kr" alt="Image" width="800" height="368" loading="lazy">
<em>Flying Fish cannot fly in the same way that birds do, however, these fish can make powerful, self-propelled leaps out of the water where their long wing-like fins enable them to glide for considerable distances above the water’s surface.</em></p>
<p>Needless to say, life on Earth is one of, if not the most successful experiments ever run in our universe; and judging from the impressive outcomes of this experiment, it is clear that evolution is clearly onto something.</p>
<p>Recently, we humans — just one of the many end products of this process — realized that we could also take advantage of this ingenious approach to progressive problem solving, and since the 1950s, computer scientist, geneticists, mathematicians, and biologist, have attempted to mimic these biological processes through the implementation of computer simulations. With the aim of producing optimal solutions for difficult, non-trivial problems, in an efficient manner.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/LdDYa7txaI3r3aOW2UnrS-U1yyIQaBhR0RzF" alt="Image" width="800" height="376" loading="lazy"></p>
<h4 id="heading-the-blind-watchmaker"><strong>The blind watchmaker</strong></h4>
<p>One of the first books I came across that sparked my interest in the field of evolutionary biology was <a target="_blank" href="https://www.goodreads.com/book/show/117047.The_Blind_Watchmaker">The Blind Watchmaker</a>, by Richard Dawkins. In this book, Richard Dawkins explains how complex mechanisms like <a target="_blank" href="https://en.wikipedia.org/wiki/Animal_echolocation">echolocation</a> (a process that bats use to navigate, hunt and forage, also known as bio-sonar), complex structures like spiderwebs (which spiders use to attract and catch their prey), and complex instruments like the human eye (those two spherical objects that you are currently using to read this article) are simply the result of thousands, if not millions of years of evolution and adaptation.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/M35jP6QH4Qor2PeQHTErVdrxHexZe1ALKB1j" alt="Image" width="800" height="1116" loading="lazy">
_The progressive evolution of the human eye. What started off as simple photosensitive cells, evolved into a complex instrument that we often take completely for granted. The first animals with anything resembling an eye lived about 550 million years ago. And, according to one [scientist’s](https://www.pbs.org/wgbh/evolution/library/01/1/l_011_01.html" rel="noopener" target="<em>blank" title=") calculations, it would only take 364,000 years for a camera-like eye to evolve from a light-sensitive patch.</em></p>
<p>Even though these marvels of nature give the impression that they were built with a purpose from the get-go (i.e by a conscious ‘maker’), they are actually just a result of iterations upon iterations of trial and error, bundled up with ever-changing selection pressure (i.e a change in climate, habitat, or the behaviour and capabilities of predators or prey). So while they may look and behave like the outcome of precise, forward-thinking engineering, they are actually the result of a completely blind process, a process that does not know beforehand what the perfect ‘solution’ would be.</p>
<h4 id="heading-what-are-genetic-algorithms-and-why-do-we-need-them"><strong>What are genetic algorithms and why do we need them?</strong></h4>
<p>Genetic algorithms are a technique used to generate high-quality solutions to optimization and search problems, which are based on fundamental biological processes. These algorithms are used in situations where the possible range of solutions is very large, and where the more basic approaches to problem-solving like exhaustive search/brute force would consume too much time and effort.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1GLH7oZafaBQavO5i0FCqqhifqkG5fRNXT39" alt="Image" width="272" height="234" loading="lazy"></p>
<p>The <a target="_blank" href="https://en.wikipedia.org/wiki/Travelling_salesman_problem">traveling salesman problem</a> asks the following question: “Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city and returns to the origin city?” It is an NP-hard problem in combinatorial optimization.</p>
<p>We can use genetic algorithms to provide high-quality solutions to this problem, at a much lower cost than the more primitive problem-solving techniques, like exhaustive search, which would require you to permute through all possible solutions.</p>
<h4 id="heading-how-do-genetic-algorithms-work"><strong>How do genetic algorithms work?</strong></h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/GWo8z30RJKWLiKSH7UOgqT8UOfFGuC0cASCq" alt="Image" width="800" height="558" loading="lazy"></p>
<p>An algorithm works by iterating through a number of steps, up until it reaches a predefined termination point. Each iteration of the genetic algorithm produces a new generation of possible solutions, which, in theory, should be an improvement on the previous generation.</p>
<p>The steps are as follows:</p>
<ol>
<li>Create an initial population of N possible solutions (the primordial soup)</li>
</ol>
<p>The first step of the algorithm is to create an initial group of solutions that serve as the base solutions in generation 0. Each solution in this initial population will carry a set of chromosomes, which are made up of a collection of genes, where each gene is assigned to one of the possible variables of the problem. It is important that the solutions in the initial population are created with randomly assigned genes, in order to have a high degree of genetic variation.</p>
<ol start="2">
<li>Rank the solutions of the population by fitness (survival of the fittest, part 1).</li>
</ol>
<p>In this step, the algorithm needs to be able to determine what makes one solution more ‘fit’ than another solution. This is determined by the fitness function. The aim of the fitness function is to evaluate the genetic viability of the solutions within the population, placing those with the most viable, favorable &amp; superior genetic traits at the top of the list.</p>
<p>In the traveling salesman problem, the fitness function could be a calculation of the total distance traveled by the solution. Where a shorter distance equates to higher fitness.</p>
<ol start="3">
<li>Cull the weaker solutions (survival of the fittest, part 2)</li>
</ol>
<p>In this step, the algorithm removes the less fit solutions from the population. The ‘fittest’ does not necessarily mean the strongest, the fastest or the fiercest, as humans usually tend to assume. Survival of the fittest simply means that the better equipped an organism is to survive in its environment, the more likely it is to live long enough to reproduce and spread its genes onto the next generation.</p>
<p>Steps 3 and 4 are collectively known as <strong>selection</strong>.</p>
<ol start="4">
<li>Breed the stronger solutions (survival of the fittest, part 3)</li>
</ol>
<p>The remaining solutions are then paired with each other in order to mate and reproduce offspring. During this process, in its most basic form, each parent will contribute a % of their genes (in nature it is a 50/50 split) to each of their offspring, where P1(G)% +P2(G)% = 100%. The process of determining which of the parents’ genes will be inherited by the offspring is known as <strong>crossover</strong>.</p>
<ol start="5">
<li>Mutate the genes of the offspring (<strong>mutation</strong>)</li>
</ol>
<p>The offspring will contain a percentage of the ‘mother’s’ genes, and a percentage of the ‘fathers’ genes and occasionally there will be a ‘mutation’ of one or more of these genes. A mutation is essentially a genetic abnormality, a copying error which causes one or more of the offspring’s genes to differ from the genes it inherited from its parents. In genetic algorithms, in some cases a mutation will increase the fitness of the offspring, in other cases, it will reduce it.</p>
<p>It is important to note that there does not need to be a mutation with each offspring, the required mutation frequency can also be a parameter of the algorithm.</p>
<p>In genetic algorithms, selection, crossover, and mutation are known as <strong>genetic operators</strong>.</p>
<ol start="6">
<li>Termination</li>
</ol>
<p>Steps 2 to 5 will be repeated up until a predefined termination point. This termination point can be one of the following:</p>
<ol>
<li>Maximum time/resource allocation reached.</li>
<li>Fixed number of generations have passed.</li>
<li>The fitness of the dominant solution cannot be surpassed by any future generations.</li>
</ol>
<h4 id="heading-solution-convergence"><strong>Solution convergence</strong></h4>
<ol>
<li>Global optimum</li>
</ol>
<p>In the ideal situation, the fittest solution will have the highest fitness value possible, i.e it will be the optimal solution, meaning that there will be no need to continue with the algorithm and produce further generations.</p>
<ol start="2">
<li>Local optimum</li>
</ol>
<p>In some cases, if the parameters of the algorithm are not reasonable, the population may tend towards a premature convergence upon a less optimal solution, which is not the global optimum that we are after, but rather a local one. Once here, continuing the algorithm and producing further generations may be futile.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/SQpPAJ72-NY7p7kJKotoBiWWYNJmJt-UmeGQ" alt="Image" width="800" height="640" loading="lazy">
<em>Global optimum vs local optimum</em></p>
<h4 id="heading-what-would-happen-if-there-were-no-mutations"><strong>What would happen if there were no mutations?</strong></h4>
<p>On first glance, mutations may seem like an unnecessary, irrelevant part of the process. But without this fundamental aspect of randomness, evolution by natural selection would be completely restricted to the genetic variety set by the initial population, and there would be no new traits introduced into the population after that. This would severely hinder nature’s problem-solving capabilities, and life on earth would not be able to ‘adapt’ to its environment, at least not physically.</p>
<p>If this was the case in our genetic algorithm, at some point in our simulation, the future generations of the population would not be able to explore part of the solution space that their predecessors did not explore. A simulation without any mutations would severely restrict the genetic variation within the population, and in most cases — depending on the initial population — prevent us from ever reaching a global optimum.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/3QFDQk2FY1jiPsvblLEuPuxzqjFMNAeawGIn" alt="Image" width="800" height="450" loading="lazy">
<em>Without mutations, we wouldn’t have mutants, and without mutants, we wouldn’t have the X-men franchise.</em></p>
<h4 id="heading-what-would-happen-if-the-population-size-was-not-large-enough"><strong>What would happen if the population size was not large enough?</strong></h4>
<p>I was recently at the Jukani Wildlife Sanctuary in Plettenberg, where I had the privilege of meeting a white tiger. He was a truly majestic animal. He was large, he looked ferocious, and, he was also 80% blind and getting progressively worse as the years went by.</p>
<p>Why was he blind? Because he is a product of generations of inbreeding. These white tigers are only produced when two tigers that carry a recessive gene controlling coat color are bred together. Thus, in order to ensure the continuation of these tigers in captivity, people have been breeding these tigers within a very limited population in order to either show them off at circuses, parade them at zoos, or keep them as household pets.</p>
<p>But one of the negative effects of inbreeding is that you severely limit the genetic variation within the species, which progressively increases the chances that harmful recessive traits will be passed onto the offspring.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/RMBs4EciPnnoKCCfrTNr4BDKJPvNKu32dRtS" alt="Image" width="800" height="450" loading="lazy">
<em>The white tiger that I met at the Jukani Wildlife Sanctuary in April 2019. He looks majestic, but he is suffering.</em></p>
<p>Even in the wild, inbreeding can still be a massive problem. Over the past few decades, the rhino population in Southern Africa has been significantly impacted due to poaching, and if the population size reaches a low enough number it would mean that maintaining the genetic diversity of these threatened rhino species would be extremely difficult. So even if poaching doesn’t completely lead them to extinction, inbreeding could.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/H3GecodM44iYchyZsSdQj1QXAusXk5oprVt-" alt="Image" width="800" height="730" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/photos/xtvo0ffGKlI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="_blank" title=""&gt;redcharlie on &lt;a href="https://unsplash.com/search/photos/black-rhino?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="<em>blank" title=").</em></p>
<p>Of course, humans are no strangers to inbreeding. One famous result of continuous inbreeding within our own species is <a target="_blank" href="http://blogs.discovermagazine.com/gnxp/2009/04/inbreeding-the-downfall-of-the-spanish-hapsburgs/#.XJO9wFMzY0o">Charles (Carlos) the II of Spain</a>.</p>
<p><em>“The Habsburg King Carlos II of Spain was sadly degenerated with an enormous misshapen head. His Habsburg jaw stood so much out that his two rows of teeth could not meet; he was unable to chew. His tongue was so large that he was barely able to speak. His intellect was similarly disabled.”</em></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/C4vGkUhe7UQOphhhbebMTt72DJNpuhy8nd6v" alt="Image" width="796" height="1024" loading="lazy">
<em>The Habsburg King Charles II of Spain. His father was his mother’s uncle, making Charles their son, great-nephew and first-cousin respectively.</em></p>
<p>‘Inbreeding’ in our genetic algorithm, essentially means the breeding of solutions that have a very similar genetic makeup, which, thankfully, in this case, would not result in offspring with a predisposition to any physical abnormalities. But if the <strong>population is very small</strong> and if <strong>all of the solutions share a very similar genetic makeup</strong> then the fitness of the future generations of the population will be severely restricted. Meaning that it could take much longer to converge upon a globally optimal solution if we even get there at all.</p>
<p>Inbreeding is not always a bad thing, it just depends on which stage of the simulation you are in. In very advanced stages of the simulation, as the population converges towards a global/local optima, it is obviously very hard to avoid inbreeding, because, in some cases, many of the dominant solutions will be very similar to each other, and thus, will share a lot of the same genetic traits.</p>
<h4 id="heading-wrapping-up">Wrapping up</h4>
<p>Alright, that should cover the basics. If you have any questions, requests, or genetic mutations to contribute, please leave a comment below.</p>
<p>In the next post, we will delve into some code as we look at how each of the genetic operators outlined above plays out in the world of programming. I used the Ruby programming language for the software simulation that I worked on, and in it, I show how in only a few generations, a genetic algorithm can produce a predefined word or phrase from an initial collection of complete and utter gibberish. All of the code will be hosted on Github.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
