So, I have to develop a simple app that measures how much time takes for a genetic algorithm to give the best answer and prints it on the screen. I've done the algorithm but something went wrong and it doesn't run the main method.
I've put the code in different online compilers, but it still didn't work.
This is the error:
.
using System;
using System.Diagnostics;
namespace GeneticTime
{
class Program
{
public struct Things
{
public int Value { get; set; }
public int Weight { get; set; }
}
static Things[] th;
static int nPop;
static int[][] Pop;
static int whLimit;
static int bestWeight;
static int bestVal;
static double[] fitness;
static int[] bestOrder;
static int nTh;
static double mutProb;
static readonly Random rand = new();
static void Main()
{
nPop = 10;
Pop = new int[nPop][];
nTh = 5;
th = new Things[nTh];
whLimit = 3000;
bestVal = 0;
bestWeight = 0;
mutProb = 0.3;
Stopwatch timer = new Stopwatch();
timer.Start();
InitPop();
InitTh();
for (int i = 0; i < 100; i++)
{
fitness = new double[nPop];
int[][] newGen = (int[][])Pop.Clone();
CalcFitness(newGen);
NormFitness();
for (int j = 0; j < nTh; i++)
{
var Parent1 = PickOne();
var Parent2 = PickOne();
newGen[j] = Crossover(Parent1, Parent2);
Mutation(newGen[j], mutProb);
}
Pop = (int[][])newGen.Clone();
timer.Stop();
Console.WriteLine("{0}", i);
}
}
static void InitPop()
{
for (int i = 0; i < nPop; i++)
Pop[i] = new int[nTh];
}
static void InitTh()
{
for (int i = 0; i < nTh; i++)
{
th[i].Value = i;
th[i].Weight = i;
}
}
static (int val, int wh) Fitness(int[] order)
{
int sumVal = 0;
int sumWeight = 0;
for (int i = 0; i < nTh; i++)
{
if (order[i] == 1)
{
sumVal += th[i].Value;
sumWeight += th[i].Weight;
}
}
if (sumVal > whLimit)
sumVal = 0;
return (sumVal, sumWeight);
}
static void CalcFitness(int[][] Gen)
{
int val;
int wh;
for (int i = 0; i < nPop; i++)
{
(val, wh) = Fitness(Gen[i]);
if (val > bestVal)
{
bestVal = val;
bestWeight = wh;
bestOrder = (int[])Gen[i].Clone();
}
fitness[i] = val;
}
}
static void NormFitness()
{
double sum = 0;
for (int i = 0; i < nPop; i++)
sum += fitness[i];
for (int i = 0; i < nPop; i++)
fitness[i] = fitness[i] / sum;
}
static int[] PickOne()
{
double k = rand.NextDouble();
double s = 0;
int[] picked = new int[nPop];
for (int i = 0; i < nPop; i++)
{
s += fitness[i];
if (k < s)
{
picked = (int[])Pop[i].Clone();
break;
}
}
return picked;
}
static int[] Crossover(int[] a, int[] b)
{
int k = rand.Next(1, nTh - 2);
int[] child = new int[nTh];
for (int i = 0; i < k; i++)
child[i] = a[i];
for (int i = k; i < nTh; i++)
child[i] = b[i];
return child;
}
static void Mutation(int[] a, double Prob)
{
int i = rand.Next(nTh);
double k = rand.NextDouble();
if (k < Prob)
a[i] = -a[i];
}
}
}
for (int j = 0; j < nTh; i++)
You are increasing i
instead of j
and therefor are stuck in an infinite loop.