OneMax
The problem is to maximize the known problem OneMax.
Real solution: 50
Code:
var cor = new Cormorant();
// Create and set the genome
var genome = CreateGenome(cor);
cor.SetGenome(genome);
// Set some properties
cor.SetNumberGenerations(50);
cor.SetPopulationSize(50);
cor.SetFitnessFunction(FitnessFunction);
cor.SetCrossoverType(ECrossoverType.OnePoint);
// Optional and just for test purpose: set the solution if it is known to get the absolute and relative error
cor.SetSolution(50);
// Compute the algorithm
cor.Compute();
// Show the report
Console.WriteLine(cor.GetReport());
private static Genome CreateGenome(Cormorant cormorant)
{
var genome = new Genome();
// We create 50 genes with values 0 or 1
for (int i = 0; i < 50; i++)
{
var gene = new Gene(
name: $"{i+1}",
min: 0,
max: 2);
genome.SetGene(gene);
}
return genome;
}
private static double FitnessFunction(Individual individual)
{
var result = individual.Genotype.Genes.Sum(gene => gene.Value);
return result;
}
Output:
==================================================
Parameters
==================================================
Population size: 50
Generations: 50
Maintain: 15%
Mutation: 10%
Fitness type: Maximize
Crossover type: OnePoint
==================================================
Best individual
==================================================
Fitness: 48
Genotype:
- Gene 1, Value: 1
- Gene 2, Value: 1
- Gene 3, Value: 1
- Gene 4, Value: 1
- Gene 5, Value: 1
- Gene 6, Value: 1
- Gene 7, Value: 1
- Gene 8, Value: 1
- Gene 9, Value: 1
- Gene 10, Value: 1
- Gene 11, Value: 1
- Gene 12, Value: 1
- Gene 13, Value: 1
- Gene 14, Value: 1
- Gene 15, Value: 1
- Gene 16, Value: 1
- Gene 17, Value: 1
- Gene 18, Value: 0
- Gene 19, Value: 1
- Gene 20, Value: 0
- Gene 21, Value: 1
- Gene 22, Value: 1
- Gene 23, Value: 1
- Gene 24, Value: 1
- Gene 25, Value: 1
- Gene 26, Value: 1
- Gene 27, Value: 1
- Gene 28, Value: 1
- Gene 29, Value: 1
- Gene 30, Value: 1
- Gene 31, Value: 1
- Gene 32, Value: 1
- Gene 33, Value: 1
- Gene 34, Value: 1
- Gene 35, Value: 1
- Gene 36, Value: 1
- Gene 37, Value: 1
- Gene 38, Value: 1
- Gene 39, Value: 1
- Gene 40, Value: 1
- Gene 41, Value: 1
- Gene 42, Value: 1
- Gene 43, Value: 1
- Gene 44, Value: 1
- Gene 45, Value: 1
- Gene 46, Value: 1
- Gene 47, Value: 1
- Gene 48, Value: 1
- Gene 49, Value: 1
- Gene 50, Value: 1
==================================================
Errors
==================================================
Absolute error: 2
Relative error: 4 %
© Cormorant 2023-2025 Written by Juan Expósito | Powered by .NET 8.0