Is this the best way to implement a genetic algorithm framework? I'm just a student and wanted to know if I can improve the code that I have done. Some of the code I copied from the framework documentation:
namespace xx.xx.xx {
class Program {
static GrafoDistrito grafo;
static int total;
static void Main(string[] args) {
using (var leitura = File.OpenText(@"C:\portugal.data")) {
string sTotal = leitura.ReadLine();
total = Int32.Parse(sTotal);
grafo = new GrafoDistrito(total);
Random rnd = new Random();
for (int i = 1; i <= total; i++) {
string line = leitura.ReadLine();
string[] identificadores = line.Split(' ');
int id = Int32.Parse(identificadores[0]);
string descricao = identificadores[1];
Distrito distrito = new Distrito(id, descricao);
grafo.AdicionarVetor(distrito);
Console.WriteLine(identificadores[1]);
}
for (int j = 1; j <= total; j++) {
string line = leitura.ReadLine();
string[] identificadores = line.Split(' ');
int totalVis = identificadores.Length;
int DistAtual = Int32.Parse(identificadores[0]);
for (int u = 1; u < totalVis; u++) {
int id = Int32.Parse(identificadores[u]);
grafo.Connect(grafo.GetVertice(DistAtual), grafo.GetVertice(id));
}
}
var population = new Population();
int[] arrayD = new int[total];
for (int a = 0; a < total; a++) {
arrayD[a] = a + 1;
}
for (int u = 0; u < 100; u++) {
var chromosome = new Chromosome();
arrayD = arrayD.OrderBy(x => rnd.Next()).ToArray();
for (var j = 0; j < arrayD.Length; j++) {
chromosome.Genes.Add(new Gene(arrayD[j]));
}
chromosome.Genes.ShuffleFast();
population.Solutions.Add(chromosome);
}
var elite = new Elite(5); //criação do operador elite
var crossover = new Crossover(0.8);
var mutacao = new SwapMutate(0.02);
var gA = new GeneticAlgorithm(population, CalculateFitness);
//operators of Genetic Algorithm
gA.Operators.Add(elite);
gA.Operators.Add(crossover);
gA.Operators.Add(mutacao);
//run Genetic Algorithm
gA.Run(Terminate);
}
}
static bool Terminate(Population pop, int currentGeneration, long currentEvaluation) {
return currentGeneration >= 400;
}
static double CalculateFitness(GAF.Chromosome chromossome) {
int[] corArray = new int[chromossome.Genes.Count];
int cor;
foreach (Gene gene in chromossome.Genes) {
int id = Convert.ToInt32(gene.RealValue);
Distrito vertice = grafo.GetVertice(id);
List<int> vizinhos = grafo.GetAresta(vertice).ToList();
List<int> corVisivel = new List<int>();
foreach (int a in vizinhos) {
int vizinhoCor = corArray[a - 1];
if (vizinhoCor > 0)
corVisivel.Add(vizinhoCor);
}
cor = 1;
while (corVisivel.Contains(cor)) {
cor++;
}
corArray[id - 1] = cor;
}
int maxCor = 0;
for (int i = 0; i < corArray.Length; i++) {
if (corArray[i] > maxCor)
maxCor = corArray[i];
}
return 1/ maxCor; //o valor de retorno tem que ser entre 0 e 1. A melhor rota é o valor mais próximo de 1
}
}
}