HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Genetic algorithm implementation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
geneticimplementationalgorithm

Problem

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  rnd.Next()).ToArray();

                    for (var j = 0; j = 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 vizinhos = grafo.GetAresta(vertice).ToList();
                List corVisivel = new List();

                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  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
        }

    }
}

Solution

You can make your code shorter and more readable with LINQ.

This:

int[] arrayD = new int[total];
for (int a = 0; a < total; a++) {
    arrayD[a] = a + 1;
}


Can be replaced with:

int[] arrayD = Enumerable.Range(1, total).ToArray();


This:

arrayD = arrayD.OrderBy(x => rnd.Next()).ToArray();
for (var j = 0; j < arrayD.Length; j++) {
    chromosome.Genes.Add(new Gene(arrayD[j]));
}


Can be replaced with:

chromosome.Genes.AddRange(arrayD.OrderBy(x => rnd.Next()));


Note that arrayD does not get shuffled each time. I'm not sure if that will affect the randomness.

This:

List corVisivel = new List();
foreach (int a in vizinhos) {
    int vizinhoCor = corArray[a - 1];
    if (vizinhoCor > 0)
        corVisivel.Add(vizinhoCor);
}


Can be replaced with:

List corVisivel = vizinhos.Select(x => corArray[x - 1]).Where(x => x > 0).ToList();


This:

cor = 1;
while (corVisivel.Contains(cor)) {
    cor++;
}


Can be replaced with:

cor = Enumerable.Range(1, int.MaxValue).TakeWhile(x => corVisivel.Contains(x)).Count() + 1;


This:

int maxCor = 0;
for (int i = 0; i  maxCor)
        maxCor = corArray[i];         
}


Can be replaced with:

int maxCor = corArray.Max();


Why does Terminate() have three parameters but only use one of them? int cor; should be declared inside the foreach loop because it's not used outside of it. You can assign it on the same line that it's declared.

Code Snippets

int[] arrayD = new int[total];
for (int a = 0; a < total; a++) {
    arrayD[a] = a + 1;
}
int[] arrayD = Enumerable.Range(1, total).ToArray();
arrayD = arrayD.OrderBy(x => rnd.Next()).ToArray();
for (var j = 0; j < arrayD.Length; j++) {
    chromosome.Genes.Add(new Gene(arrayD[j]));
}
chromosome.Genes.AddRange(arrayD.OrderBy(x => rnd.Next()));
List<int> corVisivel = new List<int>();
foreach (int a in vizinhos) {
    int vizinhoCor = corArray[a - 1];
    if (vizinhoCor > 0)
        corVisivel.Add(vizinhoCor);
}

Context

StackExchange Code Review Q#132342, answer score: 2

Revisions (0)

No revisions yet.