namespace FunctionOptimizationWithGeneticSharp
public static void Main(string[] args)
GeneticAlgorithm ga = DiagonalExample();
private static GeneticAlgorithm TcoExample()
var chromosome = new FloatingPointChromosome(
new double[] { 0, 0, 0, 0 },
new double[] { maxWidth, maxHeight, maxWidth, maxHeight },
new int[] { 10, 10, 10, 10 },
new int[] { 0, 0, 0, 0 });
var population = new Population(50, 100, chromosome);
var fitness = new FuncFitness((c) =>
var fc = c as FloatingPointChromosome;
var values = fc.ToFloatingPoints();
return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
var selection = new EliteSelection();
var crossover = new UniformCrossover(0.5f);
var mutation = new FlipBitMutation();
var termination = new FitnessStagnationTermination(100);
var ga = new GeneticAlgorithm(
ga.Termination = termination;
Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance");
ga.GenerationRan += (sender, e) =>
var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
var bestFitness = bestChromosome.Fitness.Value;
if (bestFitness != latestFitness)
latestFitness = bestFitness;
var phenotype = bestChromosome.ToFloatingPoints();
"Generation {0,2}: ({1},{2}),({3},{4}) = {5}",
private static GeneticAlgorithm DiagonalExample()
var chromosome = new FloatingPointChromosome(
new double[] { 0, 0, 0, 0 },
new double[] { maxWidth, maxHeight, maxWidth, maxHeight },
new int[] { 10, 10, 10, 10 },
new int[] { 0, 0, 0, 0 });
var population = new Population(50, 100, chromosome);
var fitness = new FuncFitness((c) =>
var fc = c as FloatingPointChromosome;
var values = fc.ToFloatingPoints();
return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
var selection = new EliteSelection();
var crossover = new UniformCrossover(0.5f);
var mutation = new FlipBitMutation();
var termination = new FitnessStagnationTermination(100);
var ga = new GeneticAlgorithm(
ga.Termination = termination;
Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance");
ga.GenerationRan += (sender, e) =>
var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
var bestFitness = bestChromosome.Fitness.Value;
if (bestFitness != latestFitness)
latestFitness = bestFitness;
var phenotype = bestChromosome.ToFloatingPoints();
"Generation {0,2}: ({1},{2}),({3},{4}) = {5}",