Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Algorithms
  • Analysis of Algorithms
  • Sorting
  • Searching
  • Greedy
  • Recursion
  • Backtracking
  • Dynamic Programming
  • Divide and Conquer
  • Geometric Algorithms
  • Mathematical Algorithms
  • Pattern Searching
  • Bitwise Algorithms
  • Branch & Bound
  • Randomized Algorithms
Open In App
Next Article:
Sequence Alignment problem
Next article icon

Genetic Algorithms

Last Updated : 08 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Genetic Algorithms(GAs) are adaptive heuristic search algorithms that belong to the larger part of evolutionary algorithms. Genetic algorithms are based on the ideas of natural selection and genetics. These are intelligent exploitation of random searches provided with historical data to direct the search into the region of better performance in solution space. They are commonly used to generate high-quality solutions for optimization problems and search problems.

Genetic algorithms simulate the process of natural selection which means those species that can adapt to changes in their environment can survive and reproduce and go to the next generation. In simple words, they simulate “survival of the fittest” among individuals of consecutive generations to solve a problem. Each generation consists of a population of individuals and each individual represents a point in search space and possible solution. Each individual is represented as a string of character/integer/float/bits. This string is analogous to the Chromosome.

Foundation of Genetic Algorithms

Genetic algorithms are based on an analogy with the genetic structure and behavior of chromosomes of the population. Following is the foundation of GAs based on this analogy –  

  1. Individuals in the population compete for resources and mate
  2. Those individuals who are successful (fittest) then mate to create more offspring than others
  3. Genes from the “fittest” parent propagate throughout the generation, that is sometimes parents create offspring which is better than either parent.
  4. Thus each successive generation is more suited for their environment.

Search space

The population of individuals are maintained within search space. Each individual represents a solution in search space for given problem. Each individual is coded as a finite length vector (analogous to chromosome) of components. These variable components are analogous to Genes. Thus a chromosome (individual) is composed of several genes (variable components). 

Fitness Score

A Fitness Score is given to each individual which shows the ability of an individual to “compete”. The individual having optimal fitness score (or near optimal) are sought. 

The GAs maintains the population of n individuals (chromosome/solutions) along with their fitness scores.The individuals having better fitness scores are given more chance to reproduce than others. The individuals with better fitness scores are selected who mate and produce better offspring by combining chromosomes of parents. The population size is static so the room has to be created for new arrivals. So, some individuals die and get replaced by new arrivals eventually creating new generation when all the mating opportunity of the old population is exhausted. It is hoped that over successive generations better solutions will arrive while least fit die. 

Each new generation has on average more “better genes” than the individual (solution) of previous generations. Thus each new generations have better “partial solutions” than previous generations. Once the offspring produced having no significant difference from offspring produced by previous populations, the population is converged. The algorithm is said to be converged to a set of solutions for the problem.

Operators of Genetic Algorithms

Once the initial generation is created, the algorithm evolves the generation using following operators – 
1) Selection Operator: The idea is to give preference to the individuals with good fitness scores and allow them to pass their genes to successive generations. 
2) Crossover Operator: This represents mating between individuals. Two individuals are selected using selection operator and crossover sites are chosen randomly. Then the genes at these crossover sites are exchanged thus creating a completely new individual (offspring). For example – 

3) Mutation Operator: The key idea is to insert random genes in offspring to maintain the diversity in the population to avoid premature convergence. For example – 
 

The whole algorithm can be summarized as –  

1) Randomly initialize populations p
2) Determine fitness of population
3) Until convergence repeat:
a) Select parents from population
b) Crossover and generate new population
c) Perform mutation on new population
d) Calculate fitness for new population

Example problem and solution using Genetic Algorithms

Given a target string, the goal is to produce target string starting from a random string of the same length. In the following implementation, following analogies are made – 

  • Characters A-Z, a-z, 0-9, and other special symbols are considered as genes
  • A string generated by these characters is considered as chromosome/solution/Individual

Fitness score is the number of characters which differ from characters in target string at a particular index. So individual having lower fitness value is given more preference.  

C++




// C++ program to create target string, starting from
// random string using Genetic Algorithm
  
#include <bits/stdc++.h>
using namespace std;
  
// Number of individuals in each generation
#define POPULATION_SIZE 100
  
// Valid Genes
const string GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP"\
"QRSTUVWXYZ 1234567890, .-;:_!\"#%&/()=?@${[]}";
  
// Target string to be generated
const string TARGET = "I love GeeksforGeeks";
  
// Function to generate random numbers in given range 
int random_num(int start, int end)
{
    int range = (end-start)+1;
    int random_int = start+(rand()%range);
    return random_int;
}
  
// Create random genes for mutation
char mutated_genes()
{
    int len = GENES.size();
    int r = random_num(0, len-1);
    return GENES[r];
}
  
// create chromosome or string of genes
string create_gnome()
{
    int len = TARGET.size();
    string gnome = "";
    for(int i = 0;i<len;i++)
        gnome += mutated_genes();
    return gnome;
}
  
// Class representing individual in population
class Individual
{
public:
    string chromosome;
    int fitness;
    Individual(string chromosome);
    Individual mate(Individual parent2);
    int cal_fitness();
};
  
Individual::Individual(string chromosome)
{
    this->chromosome = chromosome;
    fitness = cal_fitness(); 
};
  
// Perform mating and produce new offspring
Individual Individual::mate(Individual par2)
{
    // chromosome for offspring
    string child_chromosome = "";
  
    int len = chromosome.size();
    for(int i = 0;i<len;i++)
    {
        // random probability 
        float p = random_num(0, 100)/100;
  
        // if prob is less than 0.45, insert gene
        // from parent 1 
        if(p < 0.45)
            child_chromosome += chromosome[i];
  
        // if prob is between 0.45 and 0.90, insert
        // gene from parent 2
        else if(p < 0.90)
            child_chromosome += par2.chromosome[i];
  
        // otherwise insert random gene(mutate), 
        // for maintaining diversity
        else
            child_chromosome += mutated_genes();
    }
  
    // create new Individual(offspring) using 
    // generated chromosome for offspring
    return Individual(child_chromosome);
};
  
  
// Calculate fitness score, it is the number of
// characters in string which differ from target
// string.
int Individual::cal_fitness()
{
    int len = TARGET.size();
    int fitness = 0;
    for(int i = 0;i<len;i++)
    {
        if(chromosome[i] != TARGET[i])
            fitness++;
    }
    return fitness;    
};
  
// Overloading < operator
bool operator<(const Individual &ind1, const Individual &ind2)
{
    return ind1.fitness < ind2.fitness;
}
  
// Driver code
int main()
{
    srand((unsigned)(time(0)));
  
    // current generation
    int generation = 0;
  
    vector<Individual> population;
    bool found = false;
  
    // create initial population
    for(int i = 0;i<POPULATION_SIZE;i++)
    {
        string gnome = create_gnome();
        population.push_back(Individual(gnome));
    }
  
    while(! found)
    {
        // sort the population in increasing order of fitness score
        sort(population.begin(), population.end());
  
        // if the individual having lowest fitness score ie. 
        // 0 then we know that we have reached to the target
        // and break the loop
        if(population[0].fitness <= 0)
        {
            found = true;
            break;
        }
  
        // Otherwise generate new offsprings for new generation
        vector<Individual> new_generation;
  
        // Perform Elitism, that mean 10% of fittest population
        // goes to the next generation
        int s = (10*POPULATION_SIZE)/100;
        for(int i = 0;i<s;i++)
            new_generation.push_back(population[i]);
  
        // From 50% of fittest population, Individuals
        // will mate to produce offspring
        s = (90*POPULATION_SIZE)/100;
        for(int i = 0;i<s;i++)
        {
            int len = population.size();
            int r = random_num(0, 50);
            Individual parent1 = population[r];
            r = random_num(0, 50);
            Individual parent2 = population[r];
            Individual offspring = parent1.mate(parent2);
            new_generation.push_back(offspring); 
        }
        population = new_generation;
        cout<< "Generation: " << generation << "\t";
        cout<< "String: "<< population[0].chromosome <<"\t";
        cout<< "Fitness: "<< population[0].fitness << "\n";
  
        generation++;
     }
     cout<< "Generation: " << generation << "\t";
    cout<< "String: "<< population[0].chromosome <<"\t";
    cout<< "Fitness: "<< population[0].fitness << "\n";
}
 
 

Java




import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
  
public class GeneticAlgorithm {
    // Number of individuals in each generation
    private static final int POPULATION_SIZE = 100;
  
    // Valid Genes
    private static final String GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890, .-;:_!\"#%&/()=?@${[]}";
  
    // Target string to be generated
    private static final String TARGET = "I love GeeksforGeeks";
  
    // Function to generate random numbers in given range
    private static int randomNum(int start, int end) {
        Random rand = new Random();
        return rand.nextInt(end - start + 1) + start;
    }
  
    // Create random genes for mutation
    private static char mutatedGenes() {
        int len = GENES.length();
        int r = randomNum(0, len - 1);
        return GENES.charAt(r);
    }
  
    // Create chromosome or string of genes
    private static String createGnome() {
        int len = TARGET.length();
        StringBuilder gnome = new StringBuilder();
        for (int i = 0; i < len; i++)
            gnome.append(mutatedGenes());
        return gnome.toString();
    }
  
    // Class representing individual in population
    private static class Individual implements Comparable<Individual> {
        String chromosome;
        int fitness;
  
        Individual(String chromosome) {
            this.chromosome = chromosome;
            fitness = calFitness();
        }
  
        // Perform mating and produce new offspring
        Individual mate(Individual par2) {
            StringBuilder childChromosome = new StringBuilder();
  
            int len = chromosome.length();
            for (int i = 0; i < len; i++) {
                // random probability
                float p = randomNum(0, 100) / 100f;
  
                // if prob is less than 0.45, insert gene from parent 1
                if (p < 0.45)
                    childChromosome.append(chromosome.charAt(i));
  
                    // if prob is between 0.45 and 0.90, insert gene from parent 2
                else if (p < 0.90)
                    childChromosome.append(par2.chromosome.charAt(i));
  
                    // otherwise insert random gene(mutate), for maintaining diversity
                else
                    childChromosome.append(mutatedGenes());
            }
  
            // create new Individual(offspring) using generated chromosome for offspring
            return new Individual(childChromosome.toString());
        }
  
        // Calculate fitness score, it is the number of characters in string which differ from target string
        private int calFitness() {
            int len = TARGET.length();
            int fitness = 0;
            for (int i = 0; i < len; i++) {
                if (chromosome.charAt(i) != TARGET.charAt(i))
                    fitness++;
            }
            return fitness;
        }
  
        @Override
        public int compareTo(Individual o) {
            return Integer.compare(this.fitness, o.fitness);
        }
    }
  
    // Driver code
    public static void main(String[] args) {
        // current generation
        int generation = 0;
  
        List<Individual> population = new ArrayList<>();
        boolean found = false;
  
        // create initial population
        for (int i = 0; i < POPULATION_SIZE; i++) {
            String gnome = createGnome();
            population.add(new Individual(gnome));
        }
  
        while (!found) {
            // sort the population in increasing order of fitness score
            Collections.sort(population);
  
            // if the individual having lowest fitness score i.e. 0 then we know that we have reached to the target
            // and break the loop
            if (population.get(0).fitness <= 0) {
                found = true;
                break;
            }
  
            // Otherwise generate new offsprings for new generation
            List<Individual> newGeneration = new ArrayList<>();
  
            // Perform Elitism, that mean 10% of fittest population goes to the next generation
            int s = (10 * POPULATION_SIZE) / 100;
            for (int i = 0; i < s; i++)
                newGeneration.add(population.get(i));
  
            // From 50% of fittest population, Individuals will mate to produce offspring
            s = (90 * POPULATION_SIZE) / 100;
            for (int i = 0; i < s; i++) {
                int len = population.size();
                int r = randomNum(0, 50);
                Individual parent1 = population.get(r);
                r = randomNum(0, 50);
                Individual parent2 = population.get(r);
                Individual offspring = parent1.mate(parent2);
                newGeneration.add(offspring);
            }
            population = newGeneration;
            System.out.print("Generation: " + generation + "\t");
            System.out.print("String: " + population.get(0).chromosome + "\t");
            System.out.println("Fitness: " + population.get(0).fitness);
  
            generation++;
        }
        System.out.print("Generation: " + generation + "\t");
        System.out.print("String: " + population.get(0).chromosome + "\t");
        System.out.println("Fitness: " + population.get(0).fitness);
    }
}
 
 

Python3




# Python3 program to create target string, starting from
# random string using Genetic Algorithm
  
import random
  
# Number of individuals in each generation
POPULATION_SIZE = 100
  
# Valid genes
GENES = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP
QRSTUVWXYZ 1234567890, .-;:_!"#%&/()=?@${[]}'''
  
# Target string to be generated
TARGET = "I love GeeksforGeeks"
  
class Individual(object):
    '''
    Class representing individual in population
    '''
    def __init__(self, chromosome):
        self.chromosome = chromosome 
        self.fitness = self.cal_fitness()
  
    @classmethod
    def mutated_genes(self):
        '''
        create random genes for mutation
        '''
        global GENES
        gene = random.choice(GENES)
        return gene
  
    @classmethod
    def create_gnome(self):
        '''
        create chromosome or string of genes
        '''
        global TARGET
        gnome_len = len(TARGET)
        return [self.mutated_genes() for _ in range(gnome_len)]
  
    def mate(self, par2):
        '''
        Perform mating and produce new offspring
        '''
  
        # chromosome for offspring
        child_chromosome = []
        for gp1, gp2 in zip(self.chromosome, par2.chromosome):    
  
            # random probability  
            prob = random.random()
  
            # if prob is less than 0.45, insert gene
            # from parent 1 
            if prob < 0.45:
                child_chromosome.append(gp1)
  
            # if prob is between 0.45 and 0.90, insert
            # gene from parent 2
            elif prob < 0.90:
                child_chromosome.append(gp2)
  
            # otherwise insert random gene(mutate), 
            # for maintaining diversity
            else:
                child_chromosome.append(self.mutated_genes())
  
        # create new Individual(offspring) using 
        # generated chromosome for offspring
        return Individual(child_chromosome)
  
    def cal_fitness(self):
        '''
        Calculate fitness score, it is the number of
        characters in string which differ from target
        string.
        '''
        global TARGET
        fitness = 0
        for gs, gt in zip(self.chromosome, TARGET):
            if gs != gt: fitness+= 1
        return fitness
  
# Driver code
def main():
    global POPULATION_SIZE
  
    #current generation
    generation = 1
  
    found = False
    population = []
  
    # create initial population
    for _ in range(POPULATION_SIZE):
                gnome = Individual.create_gnome()
                population.append(Individual(gnome))
  
    while not found:
  
        # sort the population in increasing order of fitness score
        population = sorted(population, key = lambda x:x.fitness)
  
        # if the individual having lowest fitness score ie. 
        # 0 then we know that we have reached to the target
        # and break the loop
        if population[0].fitness <= 0:
            found = True
            break
  
        # Otherwise generate new offsprings for new generation
        new_generation = []
  
        # Perform Elitism, that mean 10% of fittest population
        # goes to the next generation
        s = int((10*POPULATION_SIZE)/100)
        new_generation.extend(population[:s])
  
        # From 50% of fittest population, Individuals 
        # will mate to produce offspring
        s = int((90*POPULATION_SIZE)/100)
        for _ in range(s):
            parent1 = random.choice(population[:50])
            parent2 = random.choice(population[:50])
            child = parent1.mate(parent2)
            new_generation.append(child)
  
        population = new_generation
  
        print("Generation: {}\tString: {}\tFitness: {}".\
              format(generation,
              "".join(population[0].chromosome),
              population[0].fitness))
  
        generation += 1
  
      
    print("Generation: {}\tString: {}\tFitness: {}".\
          format(generation,
          "".join(population[0].chromosome),
          population[0].fitness))
  
if __name__ == '__main__':
    main()
 
 

C#




using System;
using System.Collections.Generic;
using System.Linq;
  
public class GeneticAlgorithm
{
    // Number of individuals in each generation
    private const int POPULATION_SIZE = 100;
  
    // Valid Genes
    private const string GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP" +
                                  "QRSTUVWXYZ 1234567890, .-;:_!\"#%&/()=?@${[]}";
  
    // Target string to be generated
    private const string TARGET = "I love GeeksforGeeks";
  
    private static readonly Random random = new Random();
  
    // Function to generate random numbers in given range
    private static int RandomNum(int start, int end)
    {
        return random.Next(start, end + 1);
    }
  
    // Create random genes for mutation
    private static char MutatedGenes()
    {
        int len = GENES.Length;
        int r = RandomNum(0, len - 1);
        return GENES[r];
    }
  
    // Create chromosome or string of genes
    private static string CreateGnome()
    {
        int len = TARGET.Length;
        char[] gnome = new char[len];
        for (int i = 0; i < len; i++)
        {
            gnome[i] = MutatedGenes();
        }
        return new string(gnome);
    }
  
    // Class representing individual in population
    private class Individual
    {
        public string Chromosome { get; }
        public int Fitness { get; }
  
        public Individual(string chromosome)
        {
            Chromosome = chromosome;
            Fitness = CalculateFitness();
        }
  
        // Calculate fitness score, it is the number of
        // characters in string which differ from target string.
        private int CalculateFitness()
        {
            return Chromosome.Zip(TARGET, (a, b) => a == b ? 0 : 1).Sum();
        }
  
        // Perform mating and produce new offspring
        public Individual Mate(Individual parent2)
        {
            char[] childChromosome = new char[Chromosome.Length];
            for (int i = 0; i < Chromosome.Length; i++)
            {
                double p = random.NextDouble();
                if (p < 0.45)
                    childChromosome[i] = Chromosome[i];
                else if (p < 0.90)
                    childChromosome[i] = parent2.Chromosome[i];
                else
                    childChromosome[i] = MutatedGenes();
            }
            return new Individual(new string(childChromosome));
        }
    }
  
    // Overloading < operator
    private class FitnessComparer : IComparer<Individual>
    {
        public int Compare(Individual ind1, Individual ind2)
        {
            return ind1.Fitness.CompareTo(ind2.Fitness);
        }
    }
  
    // Driver code
    public static void Main()
    {
        // current generation
        int generation = 0;
  
        List<Individual> population = new List<Individual>();
        bool found = false;
  
        // create initial population
        for (int i = 0; i < POPULATION_SIZE; i++)
        {
            string gnome = CreateGnome();
            population.Add(new Individual(gnome));
        }
  
        while (!found)
        {
            // sort the population in increasing order of fitness score
            population.Sort(new FitnessComparer());
  
            // if the individual having lowest fitness score ie. 
            // 0 then we know that we have reached the target
            // and break the loop
            if (population[0].Fitness == 0)
            {
                found = true;
                break;
            }
  
            // Otherwise generate new offsprings for new generation
            List<Individual> newGeneration = new List<Individual>();
  
            // Perform Elitism, that means 10% of fittest population
            // goes to the next generation
            int s = (10 * POPULATION_SIZE) / 100;
            for (int i = 0; i < s; i++)
                newGeneration.Add(population[i]);
  
            // From 50% of fittest population, Individuals
            // will mate to produce offspring
            s = (90 * POPULATION_SIZE) / 100;
            for (int i = 0; i < s; i++)
            {
                int len = population.Count;
                int r = RandomNum(0, 50);
                Individual parent1 = population[r];
                r = RandomNum(0, 50);
                Individual parent2 = population[r];
                Individual offspring = parent1.Mate(parent2);
                newGeneration.Add(offspring);
            }
            population = newGeneration;
            Console.WriteLine("Generation: " + generation + "\t" +
                              "String: " + population[0].Chromosome + "\t" +
                              "Fitness: " + population[0].Fitness);
  
            generation++;
        }
  
        Console.WriteLine("Generation: " + generation + "\t" +
                          "String: " + population[0].Chromosome + "\t" +
                          "Fitness: " + population[0].Fitness);
    }
}
 
 

Javascript




// Number of individuals in each generation
const POPULATION_SIZE = 100;
  
// Valid Genes
const GENES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP" +
              "QRSTUVWXYZ 1234567890, .-;:_!\"#%&/()=?@${[]}";
  
// Target string to be generated
const TARGET = "I love GeeksforGeeks";
  
// Function to generate random numbers in given range
function RandomNum(start, end) {
    return Math.floor(Math.random() * (end - start + 1)) + start;
}
  
// Create random genes for mutation
function MutatedGenes() {
    let len = GENES.length;
    let r = RandomNum(0, len - 1);
    return GENES.charAt(r);
}
  
// Create chromosome or string of genes
function CreateGnome() {
    let len = TARGET.length;
    let gnome = '';
    for (let i = 0; i < len; i++) {
        gnome += MutatedGenes();
    }
    return gnome;
}
  
// Class representing individual in population
class Individual {
    constructor(chromosome) {
        this.Chromosome = chromosome;
        this.Fitness = this.CalculateFitness();
    }
  
    // Calculate fitness score, it is the number of
    // characters in string which differ from target string.
    CalculateFitness() {
        let fitness = 0;
        for (let i = 0; i < this.Chromosome.length; i++) {
            if (this.Chromosome[i] !== TARGET[i]) {
                fitness++;
            }
        }
        return fitness;
    }
  
    // Perform mating and produce new offspring
    Mate(parent2) {
        let childChromosome = '';
        for (let i = 0; i < this.Chromosome.length; i++) {
            let p = Math.random();
            if (p < 0.45)
                childChromosome += this.Chromosome[i];
            else if (p < 0.90)
                childChromosome += parent2.Chromosome[i];
            else
                childChromosome += MutatedGenes();
        }
        return new Individual(childChromosome);
    }
}
  
// Overloading < operator
class FitnessComparer {
    static Compare(ind1, ind2) {
        return ind1.Fitness - ind2.Fitness;
    }
}
  
// Driver code
function Main() {
    // current generation
    let generation = 0;
  
    let population = [];
    let found = false;
  
    // create initial population
    for (let i = 0; i < POPULATION_SIZE; i++) {
        let gnome = CreateGnome();
        population.push(new Individual(gnome));
    }
  
    while (!found) {
        // sort the population in increasing order of fitness score
        population.sort((a, b) => FitnessComparer.Compare(a, b));
  
        // if the individual having lowest fitness score ie. 
        // 0 then we know that we have reached the target
        // and break the loop
        if (population[0].Fitness === 0) {
            found = true;
            break;
        }
  
        // Otherwise generate new offsprings for new generation
        let newGeneration = [];
  
        // Perform Elitism, that means 10% of fittest population
        // goes to the next generation
        let s = Math.floor((10 * POPULATION_SIZE) / 100);
        for (let i = 0; i < s; i++)
            newGeneration.push(population[i]);
  
        // From 50% of fittest population, Individuals
        // will mate to produce offspring
        s = Math.floor((90 * POPULATION_SIZE) / 100);
        for (let i = 0; i < s; i++) {
            let r = RandomNum(0, 50);
            let parent1 = population[r];
            r = RandomNum(0, 50);
            let parent2 = population[r];
            let offspring = parent1.Mate(parent2);
            newGeneration.push(offspring);
        }
        population = newGeneration;
        console.log("Generation: " + generation + "\t" +
                     "String: " + population[0].Chromosome + "\t" +
                     "Fitness: " + population[0].Fitness);
  
        generation++;
    }
  
    console.log("Generation: " + generation + "\t" +
                "String: " + population[0].Chromosome + "\t" +
                "Fitness: " + population[0].Fitness);
}
  
// Execute the main function
Main();
 
 

Output: 

Generation: 1    String: tO{"-?=jH[k8=B4]Oe@}    Fitness: 18
Generation: 2 String: tO{"-?=jH[k8=B4]Oe@} Fitness: 18
Generation: 3 String: .#lRWf9k_Ifslw #O$k_ Fitness: 17
Generation: 4 String: .-1Rq?9mHqk3Wo]3rek_ Fitness: 16
Generation: 5 String: .-1Rq?9mHqk3Wo]3rek_ Fitness: 16
Generation: 6 String: A#ldW) #lIkslw cVek) Fitness: 14
Generation: 7 String: A#ldW) #lIkslw cVek) Fitness: 14
Generation: 8 String: (, o x _x%Rs=, 6Peek3 Fitness: 13
.
.
.
Generation: 29 String: I lope Geeks#o, Geeks Fitness: 3
Generation: 30 String: I loMe GeeksfoBGeeks Fitness: 2
Generation: 31 String: I love Geeksfo0Geeks Fitness: 1
Generation: 32 String: I love Geeksfo0Geeks Fitness: 1
Generation: 33 String: I love Geeksfo0Geeks Fitness: 1
Generation: 34 String: I love GeeksforGeeks Fitness: 0

Note: Every-time algorithm start with random strings, so output may differ

As we can see from the output, our algorithm sometimes stuck at a local optimum solution, this can be further improved by updating fitness score calculation algorithm or by tweaking mutation and crossover operators.

Why use Genetic Algorithms 

  • They are Robust
  • Provide optimisation over large space state.
  • Unlike traditional AI, they do not break on slight change in input or presence of noise

Application of Genetic Algorithms

Genetic algorithms have many applications, some of them are – 

  • Recurrent Neural Network
  • Mutation testing
  • Code breaking
  • Filtering and signal processing
  • Learning fuzzy rule base etc



Next Article
Sequence Alignment problem

A

Atul Kumar
Improve
Article Tags :
  • Algorithms
  • DSA
Practice Tags :
  • Algorithms

Similar Reads

  • Traveling Salesman Problem using Genetic Algorithm
    AuPrerequisites: Genetic Algorithm, Travelling Salesman ProblemIn this article, a genetic algorithm is proposed to solve the travelling salesman problem. Genetic algorithms are heuristic search algorithms inspired by the process that supports the evolution of life. The algorithm is designed to repli
    15+ min read
  • Mutation Algorithms for String Manipulation (GA)
    Genetic Algorithms(GAs) are adaptive heuristic search algorithms that belong to the larger part of evolutionary algorithms. In each generation chromosomes(our solution candidates) undergo mutation and crossover and then selection to produce a better population whose candidates are nearer to our desi
    2 min read
  • Mutation Algorithms for Real-Valued Parameters (GA)
    Genetic Algorithms(GAs) are adaptive heuristic search algorithms that belong to the larger part of evolutionary algorithms. In each generation chromosomes(our solution candidates) undergo mutation and crossover and selection to produce a better population whose chromosomes are nearer to our desired
    3 min read
  • Sequence Alignment problem
    Given as an input two strings, [Tex]X [/Tex]= [Tex]x_{1} x_{2}... x_{m} [/Tex], and [Tex]Y [/Tex]= [Tex]y_{1} y_{2}... y_{m} [/Tex], output the alignment of the strings, character by character, so that the net penalty is minimized. The penalty is calculated as: A penalty of [Tex]p_{gap} [/Tex]occurs
    15+ min read
  • Tournament Selection (GA)
    Tournament Selection is a Selection Strategy used for selecting the fittest candidates from the current generation in a Genetic Algorithm. These selected candidates are then passed on to the next generation. In a K-way tournament selection, we select k-individuals and run a tournament among them. On
    2 min read
  • Longest mutation sequence
    Given a list of conversion tuples Arr[], such that string Arr[i][0] gets converted to string Arr[i][1]. A character is considered good if it has one-to-one mapping to some other character throughout all the conversions, for example during conversion of "abb" to "abc", b->c is considered good. You
    9 min read
  • Program for Conway's Game Of Life | Set 1
    Given a Binary Matrix mat[][] of order m*n. A cell with a value of zero is a Dead Cell, while a cell with a value of one is a Live Cell. The state of cells in a matrix mat[][] is known as Generation. The task is to find the next generation of cells based on the following rules: Any live cell with fe
    12 min read
  • Program for Conway’s Game Of Life | Set 2
    Given a Binary Matrix mat[][] of order m*n. A cell with a value of zero is a Dead Cell, while a cell with a value of one is a Live Cell. The state of cells in a matrix mat[][] is known as Generation. The task is to find the next generation of cells based on the following rules: Any live cell with fe
    12 min read
  • Puzzle | The Apocalypse
    Puzzle:In the new post-apocalyptic world, the world queen is desperately concerned about the birth rate. Therefore, she decrees that all families should ensure that they have one girl or else they face massive fines. If all families abide by this policy-that is, they have continued to have children
    4 min read
  • Find profession in a special family
    Consider a special family of Engineers and Doctors with following rules : Everybody has two children.First child of an Engineer is an Engineer and second child is a Doctor.First child of an Doctor is Doctor and second child is an Engineer.All generations of Doctors and Engineers start with Engineer.
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences