Matrix of objects class - c#

I have written 3 classes: KompresorSilnik, KompresorObiekt and Mrowka.
I want to create a matrix of objects of class KompresorObiekt ( it's a GrafObiektow method ). In the constructor of KompresorObiekt, I create 4 instances of KompresorSilnik. I have a method, zwrocListe() which returns a list of int[] from 0000 to 2222.
The question is: was that correct or not implementation?
public class KompresorSilnik
{
public double minFlow;
public double maxFlow;
public bool typ;
public int stan;
public KompresorSilnik()
{
}
public KompresorSilnik(double minFlow, double maxFlow, bool typ, int stan)
{
this.minFlow = minFlow;
this.maxFlow = maxFlow;
this.typ = typ;
this.stan = stan;
}
}
This is my second class KompresorObiekt
public class KompresorObiekt
{
public KompresorObiekt() { }
public KompresorObiekt( List<int[]> list, int x, int y)
{
double k1Max = 3000000.0;
double k1Min = 10000.0;
double k2Max = 200000.0;
double k2Min = 5000.0;
double K3Max = 100000000.0;
double k3Min = 800.0;
double k4Max = 10000.0;
double k4Min = 2000.0;
KompresorSilnik komp1 = new KompresorSilnik(k1Min, k1Max, false, list[x][y]);
KompresorSilnik komp2 = new KompresorSilnik(k2Min, k2Max, true, list[x][y+1]);
KompresorSilnik komp3 = new KompresorSilnik(k3Min, K3Max, false, list[x][y+2]);
KompresorSilnik komp4 = new KompresorSilnik(k4Min, k4Max, true, list[x][y+3]);
}
}
and the last one Mrowka
public class Mrowka
{
List<int[]> zwrocListe()
{
List<int[]> arrList = new List<int[]>();
int[] ArrayOfInts = new int[4];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
for (int m = 0; m < 3; m++)
{
ArrayOfInts[0] = i;
ArrayOfInts[1] = j;
ArrayOfInts[2] = k;
ArrayOfInts[3] = m;
int[] arc = (int[])ArrayOfInts.Clone();
arrList.Add(arc);
}
}
}
}
return arrList;
}
KompresorObiekt[][] GrafObiektow(int time)
{
KompresorObiekt[][] graf = new KompresorObiekt[time][];
int numNodes = zwrocListe().Count;
for (int i = 0; i < graf.Length; ++i)
graf[i] = new KompresorObiekt[numNodes];
for (int i = 0; i < time; ++i)
for (int j = 0; j < numNodes; ++j)
{
graf[i][j] = new KompresorObiekt(zwrocListe(), j, 0);
}
return graf;
}
}

Related

I got a stack overflow error and I can't figure out what causes it

I am trying to generate a maze and I faced a stack overflow error while trying to do divide and conquer kind of approach to my 2D array.I will have to post the whole code since I have no idea what causes it and i am very inexperienced in the subject.
this is the details : System.StackOverflowException
HResult=0x800703E9
Message=
this is where the exception happens
!https://imgur.com/a/iwX8pKY
https://www.robinsnyder.com/MazeStaticGif I got the idea from here.
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
namespace labirentVize2
{
class labirentOlustur
{ public static int delik;
public static int x=0;
public static int y;
public static int N = 30;
public static int boy = 30;
int[,] uret = new int[N, N];
public Array girisCikis(int[,] uret)
{
int en1=1;
Random giris = new Random();
int gir = giris.Next(1, 29);
if (gir > 14)
{
int gir2 = giris.Next(15, 28);
int gir3 = (gir + gir2)/2;
uret[0, gir] = 1;
uret[0, gir2] = 1;
uret[0, gir3] = 1;
}
else
{
int gir2 = giris.Next(1, 15);
int gir3 = (gir + gir2)/2;
uret[0, gir] = 1;
uret[0, gir2] = 1;
uret[0, gir3] = 1;
}
Random cikis = new Random();
int cik = cikis.Next(1, 28);
if (cik > 14)
{
int cik2 = cikis.Next(1, 28);
int cik3 = (cik + cik2)/2;
uret[29, cik] = 1;
uret[29, cik2] = 1;
uret[29, cik3] = 1;
}
else
{
int cik2 = cikis.Next(15, 28);
int cik3 = (cik + cik2)/2;
uret[29, cik] = 1;
uret[29, cik2] = 1;
uret[29, cik3] = 1;
}
labYap(uret, en1, x, boy);
return uret;
}
void labGoster(int[,] uret)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
Console.Write(" " + uret[i, j] + " ");
Console.WriteLine();
}
}
public void labYap(int[,] uret, int en1, int x, int boy)
{
int total1 = 0;
Random rand2 = new Random();
for (int i = 0; i < uret.GetLength(0); i++)
{
for (int j = 0; j < uret.GetLength(1); j++)
{
total1 += uret[i, j];}
}
if(total1 > 800)
{
labGoster(uret);
}
else if (total1 == 784)
{
Random rand1 = new Random();
en1 = rand1.Next(2, 29);
x = 30;
delik = rand2.Next(1, 29);
}
else
{
Random rand = new Random();
en1 = rand.Next(1, en1);
boy = boy - en1;
delik = rand2.Next(1, en1);
}
if (diziUstToplam(uret, en1) >= diziAltToplam(uret, en1))
{
y = en1;
for (int j = 0; j < x ; j++)
{
uret[en1, j] = 0;
}
uret[en1, delik] = 1;
labYap(uret, en1, x, boy);
labYap(uret, boy, x, boy);
}
else
{ x = en1;
for (int j = 0; j < en1; j++)
{
uret[j, en1] = 0;
}
uret[delik, en1] = 1;
labYap(uret, en1, x, boy);
labYap(uret, en1, x, boy);
}
int diziUstToplam(int[,] uret, int en1)
{
int total = 0;
// Dizinin ilk boyutu için
for (int i = 0; i < en1; i++)
{
// Dizinin ikinci boyutu için
for (int j = 0; j < uret.GetLength(1); j++)
{
total += uret[i, j];
}
}
return total;
}
int diziAltToplam(int[,] uret, int en1)
{
int total = 0;
// Dizinin ilk boyutu için
for (int i = en1; i < 30; i++)
{
// Dizinin ikinci boyutu için
for (int j = 0; j < uret.GetLength(1); j++)
{
total += uret[i, j];
}
}
return total;
}
int rastgeleSayi()
{
Random rand = new Random();
int en1 = rand.Next(1, 29);
return en1;
}
}
}
}
The stack overflow error is because you call labYear() too many times from within itself. You need to ensure that you have some escape condition where the function can return.
See more here: https://learn.microsoft.com/en-us/dotnet/api/system.stackoverflowexception?view=net-6.0

return data from method c#

I use this method and need return weights8spr, but I don't know how.
Can anybody help me? simplest return(weights8spr) don't work, because in input Im not give the double array.
public class Run {
public Run(List<dataVM2> TrainDataForStations)
{
double[] resultMAX1 = new double[] { 40.0, 1200.0, 100.0, 100.0, 10000.0 };
double[] resultMIN1 = new double[] { -50.0, 0.0, 0.0, 0.0, 0.0 };
double d1 = 0.0;
double d2 = 1.0;
int numItemsspr = TrainDataForStations.Count;
double[][] trainData = new double[numItemsspr][];
Random rnd = new Random(1);
double[][] MassiveDataspr8 = new double[numItemsspr][];
for (var i = 0; i < numItemsspr; ++i)
{
trainData[i] = new double[] { TrainDataForStations[i].TemperatureC1, TrainDataForStations[i].SolarRadiation1, TrainDataForStations[i].Wetness1, TrainDataForStations[i].WindSpeed1, TrainDataForStations[i].gen1 };
}
int maxcol = 0;
for (int i = 0; i < trainData.Length; i++)
{
if (trainData[i].Length > maxcol)
maxcol = trainData[i].Length;
}
//data normalization
for (int j = 0; j < MassiveDataspr8.Length; j++)
{
MassiveDataspr8[j] = new double[maxcol];
for (int i = 0; i < maxcol; i++)
{
MassiveDataspr8[j][i] = (((trainData[j][i] - resultMIN1[i]) * (d2 - d1)) / (resultMAX1[i] - resultMIN1[i])) + d1;
}
}
int NumInput = 4;
int NumHidden = 25;
int NumOutput = 1;
int rndSeed = 0;
NeuralNetworkData neuralform = new NeuralNetworkData(NumInput, NumHidden, NumOutput, rnd);
int maxEpochs = 1000;
double learnRate = 0.005;
double momentum = 0.001;
double[] weights8spr = new NeuralNetworkTrainer(neuralform, rnd).Train(MassiveDataspr8, maxEpochs, learnRate, momentum);
}
}
You are executing that code in the constructor of a class and you can't change the return type of a constructor.
You should create a method in the class and refactor the code a little.
public class Run
{
// default constructor not needed
public Run()
{
}
public double[] RunMethod(List<dataVM2> TrainDataForStations)
{
// put your code here
// ...
// return the double[]
return weights8spr;
}
}
And execute like:
var run = new Run();
var weights = run.RunMethod(listOfTrainDataForStations);
A method must have a return type. If it doesn't return a value, then this would be the pseudo type void, otherwise a real one.
public class StationsTrainer {
public double[] Run(List<dataVM2> TrainDataForStations)
{
...
double[] weights8spr = new NeuralNetworkTrainer(neuralform, rnd)
.Train(MassiveDataspr8, maxEpochs, learnRate, momentum);
return weights8spr;
}
}
And choose a better name for the class. E.g. StationsTrainer.

My code is showing compiler erros and I dont know why even though the code seems correct

Ok so I finished my code n queens genetics in c# but I keep getting these compiler errors even though I changed the code several times
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NQueen1
{
class Program
{
private const int sSize = 75; // Population size at start.
private const int mTest = 1000; // Arbitrary number of test cycles.
private const double pMating = 0.7; // Probability of two chromosomes mating. Range: 0.0 < MATING_PROBABILITY < 1.0
private const double rMutation = 0.001; // Mutation Rate. Range: 0.0 < MUTATION_RATE < 1.0
private const int minS = 10; // Minimum parents allowed for selection.
private const int MaxS = 50; // Maximum parents allowed for selection. Range: MIN_SELECT < MAX_SELECT < START_SIZE
private const int offSpring = 20; // New offspring created per generation. Range: 0 < OFFSPRING_PER_GENERATION < MAX_SELECT.
private const int minRandom = 8; // For randomizing starting chromosomes
private const int maxShuffles = 20;
private const int maxPBC = 4; // Maximum Position-Based Crossover points. Range: 0 < PBC_MAX < 8 (> 8 isn't good).
private const int maxLength = 10; // chess board width.
private static int epoch = 0;
private static int childCount = 0;
private static int nextMutation = 0; // For scheduling mutations.
private static int mutations = 0;
private static List<Chromosome> population = new List<Chromosome>();
private static void algorithm()
{
int popSize = 0;
Chromosome thisChromo = null;
bool done = false;
initializeChromosomes();
mutations = 0;
nextMutation = getRandomNumber(0, (int)Math.Round(1.0 / rMutation));
while (!done)
{
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
if ((thisChromo.conflicts() == 0) || epoch == mTest)
{
done = true;
}
}
getFitness();
rouletteSelection();
mating();
prepNextEpoch();
epoch++;
// This is here simply to show the runtime status.
Console.WriteLine("Epoch: " + epoch);
}
Console.WriteLine("done.");
if (epoch != rMutation)
{
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
if (thisChromo.conflicts() == 0)
{
printSolution(thisChromo);
}
}
}
Console.WriteLine("Completed " + epoch + " epochs.");
Console.WriteLine("Encountered " + mutations + " mutations in " + childCount + " offspring.");
return;
}
private static void getFitness()
{
// Lowest errors = 100%, Highest errors = 0%
int popSize = population.Count;
Chromosome thisChromo = null;
double bestScore = 0;
double worstScore = 0;
// The worst score would be the one with the highest energy, best would be lowest.
worstScore = population[maximum()].conflicts();
// Convert to a weighted percentage.
bestScore = worstScore - population[minimum()].conflicts();
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
thisChromo.fitness((worstScore - thisChromo.conflicts()) * 100.0 / bestScore);
}
return;
}
private static void rouletteSelection()
{
int j = 0;
int popSize = population.Count;
double genT = 0.0;
double selT = 0.0;
int maximumToSelect = getRandomNumber(minS, MaxS);
double rouletteSpin = 0.0;
Chromosome thisChromo = null;
Chromosome thatChromo = null;
bool done = false;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
genT += thisChromo.fitness();
}
genT *= 0.01;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
thisChromo.selectionProbability(thisChromo.fitness() / genT);
}
for (int i = 0; i < maximumToSelect; i++)
{
rouletteSpin = getRandomNumber(0, 99);
j = 0;
selT = 0;
done = false;
while (!done)
{
thisChromo = population[j];
selT += thisChromo.selectionProbability();
if (selT >= rouletteSpin)
{
if (j == 0)
{
thatChromo = population[j];
}
else if (j >= popSize - 1)
{
thatChromo = population[popSize - 1];
}
else
{
thatChromo = population[j - 1];
}
thatChromo.selected(true);
done = true;
}
else
{
j++;
}
}
}
return;
}
// This is where you can choose between options:
// To choose between crossover options, uncomment one of:
// partiallyMappedCrossover(),
// positionBasedCrossover(), while keeping the other two commented out.
private static void mating()
{
int getRand = 0;
int parentA = 0;
int parentB = 0;
int newIndex1 = 0;
int newIndex2 = 0;
Chromosome newChromo1 = null;
Chromosome newChromo2 = null;
for (int i = 0; i < offSpring; i++)
{
parentA = chooseParent();
// Test probability of mating.
getRand = getRandomNumber(0, 100);
if (getRand <= pMating * 100)
{
parentB = chooseParent(parentA);
newChromo1 = new Chromosome();
newChromo2 = new Chromosome();
population.Add(newChromo1);
newIndex1 = population.IndexOf(newChromo1);
population.Add(newChromo2);
newIndex2 = population.IndexOf(newChromo2);
// Choose either, or both of these:
partialCrossover(parentA, parentB, newIndex1, newIndex2);
//positionBasedCrossover(parentA, parentB, newIndex1, newIndex2);
if (childCount - 1 == nextMutation)
{
exchangeMutation(newIndex1, 1);
}
else if (childCount == nextMutation)
{
exchangeMutation(newIndex2, 1);
}
population[newIndex1].computeConflicts();
population[newIndex2].computeConflicts();
childCount += 2;
// Schedule next mutation.
if (childCount % (int)Math.Round(1.0 / rMutation) == 0)
{
nextMutation = childCount + getRandomNumber(0, (int)Math.Round(1.0 / rMutation));
}
}
} // i
return;
}
private static void partialCrossover(int chromA, int chromB, int child1, int child2)
{
int j = 0;
int item1 = 0;
int item2 = 0;
int pos1 = 0;
int pos2 = 0;
Chromosome thisChromo = population[chromA];
Chromosome thatChromo = population[chromB];
Chromosome newChromo1 = population[child1];
Chromosome newChromo2 = population[child2];
int crossPoint1 = getRandomNumber(0, maxLength - 1);
int crossPoint2 = getExclusiveRandomNumber(maxLength - 1, crossPoint1);
if (crossPoint2 < crossPoint1)
{
j = crossPoint1;
crossPoint1 = crossPoint2;
crossPoint2 = j;
}
// Copy Parent genes to offspring.
for (int i = 0; i < maxLength; i++)
{
newChromo1.data(i, thisChromo.data(i));
newChromo2.data(i, thatChromo.data(i));
}
for (int i = crossPoint1; i <= crossPoint2; i++)
{
// Get the two items to swap.
item1 = thisChromo.data(i);
item2 = thatChromo.data(i);
// Get the items// positions in the offspring.
for (j = 0; j < maxLength; j++)
{
if (newChromo1.data(j) == item1)
{
pos1 = j;
}
else if (newChromo1.data(j) == item2)
{
pos2 = j;
}
} // j
// Swap them.
if (item1 != item2)
{
newChromo1.data(pos1, item2);
newChromo1.data(pos2, item1);
}
// Get the items// positions in the offspring.
for (j = 0; j < maxLength; j++)
{
if (newChromo2.data(j) == item2)
{
pos1 = j;
}
else if (newChromo2.data(j) == item1)
{
pos2 = j;
}
} // j
// Swap them.
if (item1 != item2)
{
newChromo2.data(pos1, item1);
newChromo2.data(pos2, item2);
}
} // i
return;
}
private static void positionCrossover(int chromA, int chromB, int child1, int child2)
{
int k = 0;
int numPoints = 0;
int[] tempArray1 = new int[maxLength];
int[] tempArray2 = new int[maxLength];
bool matchFound = false;
Chromosome thisChromo = population[chromA];
Chromosome thatChromo = population[chromB];
Chromosome newChromo1 = population[child1];
Chromosome newChromo2 = population[child2];
// Choose and sort the crosspoints.
numPoints = getRandomNumber(0, maxPBC);
int[] crossPoints = new int[numPoints];
int negativeNancy = -1;
for (int i = 0; i < numPoints; i++)
{
crossPoints[i] = getRandomNumber(0, maxLength - negativeNancy, crossPoints);
} // i
// Get non-chosens from parent 2
k = 0;
for (int i = 0; i < maxLength; i++)
{
matchFound = false;
for (int j = 0; j < numPoints; j++)
{
if (thatChromo.data(i) == thisChromo.data(crossPoints[j]))
{
matchFound = true;
}
} // j
if (matchFound == false)
{
tempArray1[k] = thatChromo.data(i);
k++;
}
} // i
// Insert chosens into child 1.
for (int i = 0; i < numPoints; i++)
{
newChromo1.data(crossPoints[i], thisChromo.data(crossPoints[i]));
}
// Fill in non-chosens to child 1.
k = 0;
for (int i = 0; i < maxLength; i++)
{
matchFound = false;
for (int j = 0; j < numPoints; j++)
{
if (i == crossPoints[j])
{
matchFound = true;
}
} // j
if (matchFound == false)
{
newChromo1.data(i, tempArray1[k]);
k++;
}
} // i
// Get non-chosens from parent 1
k = 0;
for (int i = 0; i < maxLength; i++)
{
matchFound = false;
for (int j = 0; j < numPoints; j++)
{
if (thisChromo.data(i) == thatChromo.data(crossPoints[j]))
{
matchFound = true;
}
} // j
if (matchFound == false)
{
tempArray2[k] = thisChromo.data(i);
k++;
}
} // i
// Insert chosens into child 2.
for (int i = 0; i < numPoints; i++)
{
newChromo2.data(crossPoints[i], thatChromo.data(crossPoints[i]));
}
// Fill in non-chosens to child 2.
k = 0;
for (int i = 0; i < maxLength; i++)
{
matchFound = false;
for (int j = 0; j < numPoints; j++)
{
if (i == crossPoints[j])
{
matchFound = true;
}
} // j
if (matchFound == false)
{
newChromo2.data(i, tempArray2[k]);
k++;
}
} // i
return;
}
private static void exchangeMutation(int index, int exchanges)
{
int i = 0;
int tempData = 0;
Chromosome thisChromo = null;
int gene1 = 0;
int gene2 = 0;
bool done = false;
thisChromo = population[index];
while (!done)
{
gene1 = getRandomNumber(0, maxLength - 1);
gene2 = getExclusiveRandomNumber(maxLength - 1, gene1);
// Exchange the chosen genes.
tempData = thisChromo.data(gene1);
thisChromo.data(gene1, thisChromo.data(gene2));
thisChromo.data(gene2, tempData);
if (i == exchanges)
{
done = true;
}
i++;
}
mutations++;
return;
}
private static int chooseParent()
{
// Overloaded function, see also "chooseparent(ByVal parentA As Integer)".
int parent = 0;
Chromosome thisChromo = null;
bool done = false;
while (!done)
{
// Randomly choose an eligible parent.
parent = getRandomNumber(0, population.Count - 1);
thisChromo = population[parent];
if (thisChromo.selected() == true)
{
done = true;
}
}
return parent;
}
{
// Overloaded function, see also "chooseparent()".
int parent = 0;
Chromosome thisChromo = null;
bool done = false;
while (!done)
{
// Randomly choose an eligible parent.
parent = getRandomNumber(0, population.Count - 1);
if (parent != parentA)
{
thisChromo = population[parent];
if (thisChromo.selected() == true)
{
done = true;
}
}
}
return parent;
}
private static void prepNextEpoch()
{
int popSize = 0;
Chromosome thisChromo = null;
// Reset flags for selected individuals.
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
thisChromo = population[i];
thisChromo.selected(false);
}
return;
}
private static void printSolution(Chromosome bestSolution)
{
string[][] board = RectangularArrays.ReturnRectangularStringArray(maxLength, maxLength);
// Clear the board.
for (int x = 0; x < maxLength; x++)
{
for (int y = 0; y < maxLength; y++)
{
board[x][y] = "";
}
}
for (int x = 0; x < maxLength; x++)
{
board[x][bestSolution.data(x)] = "Q";
}
// Display the board.
Console.WriteLine("Board:");
for (int y = 0; y < maxLength; y++)
{
for (int x = 0; x < maxLength; x++)
{
if (string.ReferenceEquals(board[x][y], "Q"))
{
Console.Write("Q ");
}
else
{
Console.Write(". ");
}
}
Console.Write("\n");
}
return;
}
private static int getRandomNumber(int low, int high)
{
return (int)Math.Round((high - low) * (new Random()).NextDouble() + low);
}
private static int getExclusiveRandomNumber(int high, int except)
{
bool done = false;
int getRand = 0;
while (!done)
{
getRand = (new Random()).Next(high);
if (getRand != except)
{
done = true;
}
}
return getRand;
}
private static int getRandomNumber(int low, int high, int[] except)
{
bool done = false;
int getRand = 0;
if (high != low)
{
while (!done)
{
done = true;
getRand = (int)Math.Round((high - low) * (new Random()).NextDouble() + low);
for (int i = 0; i < except.Length; i++) //UBound(except)
{
if (getRand == except[i])
{
done = false;
}
} // i
}
return getRand;
}
else
{
return high; // or low (it doesn't matter).
}
}
private static int minimum()
{
// Returns an array index.
int popSize = 0;
Chromosome thisChromo = null;
Chromosome thatChromo = null;
int winner = 0;
bool foundNewWinner = false;
bool done = false;
while (!done)
{
foundNewWinner = false;
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
if (i != winner)
{ // Avoid self-comparison.
thisChromo = population[i];
thatChromo = population[winner];
if (thisChromo.conflicts() < thatChromo.conflicts())
{
winner = i;
foundNewWinner = true;
}
}
}
if (foundNewWinner == false)
{
done = true;
}
}
return winner;
}
private static int maximum()
{
// Returns an array index.
int popSize = 0;
Chromosome thisChromo = null;
Chromosome thatChromo = null;
int winner = 0;
bool foundNewWinner = false;
bool done = false;
while (!done)
{
foundNewWinner = false;
popSize = population.Count;
for (int i = 0; i < popSize; i++)
{
if (i != winner)
{ // Avoid self-comparison.
thisChromo = population[i];
thatChromo = population[winner];
if (thisChromo.conflicts() > thatChromo.conflicts())
{
winner = i;
foundNewWinner = true;
}
}
}
if (foundNewWinner == false)
{
done = true;
}
}
return winner;
}
private static void initializeChromosomes()
{
int shuffles = 0;
Chromosome newChromo = null;
int chromoIndex = 0;
for (int i = 0; i < sSize; i++)
{
newChromo = new Chromosome();
population.Add(newChromo);
chromoIndex = population.IndexOf(newChromo);
// Randomly choose the number of shuffles to perform.
shuffles = getRandomNumber(minRandom, maxShuffles);
exchangeMutation(chromoIndex, shuffles);
population[chromoIndex].computeConflicts();
}
return;
}
private class Chromosome
{
internal int[] mData = new int[maxLength];
internal double mFitness = 0.0;
internal bool mSelected = false;
internal double mSelectionProbability = 0.0;
internal int mConflicts = 0;
public Chromosome()
{
for (int i = 0; i < maxLength; i++)
{
this.mData[i] = i;
}
return;
}
public virtual void computeConflicts()
{
int x = 0;
int y = 0;
int tempx = 0;
int tempy = 0;
//string[][] board = new string[MAX_LENGTH][MAX_LENGTH];
string[][] board = RectangularArrays.ReturnRectangularStringArray(maxLength, maxLength);
int conflicts = 0;
int[] dx = new int[] { -1, 1, -1, 1 };
int[] dy = new int[] { -1, 1, 1, -1 };
bool done = false;
// Clear the board.
for (int i = 0; i < maxLength; i++)
{
for (int j = 0; j < maxLength; j++)
{
board[i][j] = "";
}
}
for (int i = 0; i < maxLength; i++)
{
board[i][this.mData[i]] = "Q";
}
// Walk through each of the Queens and compute the number of conflicts.
for (int i = 0; i < maxLength; i++)
{
x = i;
y = this.mData[i];
// Check diagonals.
for (int j = 0; j <= 3; j++)
{
tempx = x;
tempy = y;
done = false;
while (!done)
{
tempx += dx[j];
tempy += dy[j];
if ((tempx < 0 || tempx >= maxLength) || (tempy < 0 || tempy >= maxLength))
{
done = true;
}
else
{
if (board[tempx][tempy].ToString().ToUpper().Equals("Q"))// ignore the case of 2 strings
{
conflicts++;
}
}
}
}
}
this.mConflicts = conflicts;
}
public virtual void conflicts(int value)
{
this.mConflicts = value;
return;
}
public virtual int conflicts()
{
return this.mConflicts;
}
public virtual double selectionProbability()
{
return mSelectionProbability;
}
public virtual void selectionProbability(double SelProb)
{
mSelectionProbability = SelProb;
return;
}
public virtual bool selected()
{
return mSelected;
}
public virtual void selected(bool sValue)
{
mSelected = sValue;
return;
}
public virtual double fitness()
{
return mFitness;
}
public virtual void fitness(double score)
{
mFitness = score;
return;
}
public virtual int data(int index)
{
return mData[index];
}
public virtual void data(int index, int value)
{
mData[index] = value;
return;
}
} // Chromosome
static void Main(string[] args)
{
algorithm();
return;
}
}
}
This is the second code here:
namespace NQueen1
{
internal static class RectangularArrays
{
internal static string[][] ReturnRectangularStringArray(int size1, int size2)
{
string[][] newArray = new string[size1][];
for (int array1 = 0; array1 < size1; array1++)
{
newArray[array1] = new string[size2];
}
return newArray;
}
}
}
THe Error:
Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
at System.Collections.Generic.List`1.get_Item(Int32 index)
at NQueen1.Program.rouletteSelection() in C:\Users\Inspiron\Documents\coid\NQueen1\NQueen1\Program.cs:line 143
at NQueen1.Program.algorithm() in C:\Users\Inspiron\Documents\coid\NQueen1\NQueen1\Program.cs:line 56
at NQueen1.Program.Main(String[] args) in C:\Users\Inspiron\Documents\coid\NQueen1\NQueen1\Program.cs:line 841
I have no clue why its throwing off these errors I tried about almost everything I could think of to fix it
This is just a random guess.
My Spidey Senses tells me thisChromo = population[j] is probably overrunning the size of array, i.e. its in a while loop with j++ and there is no real bounds checking
private static void rouletteSelection()
{
...
for (int i = 0; i < maximumToSelect; i++)
{
...
while (!done)
{
thisChromo = population[j];
...
j++;
If this is the problem, I'd consider the possibility that j will be larger than population.Length and therefore breaking out of the loop; using an if statement; or just refactoring this logic
Tips for your future questions
If you have a runtime error, show us the line of code it has the error on
Pasting code is vital, however pasting too much is annoying and hard to read
If you paste code, at least try to format it
Learn to use the debugger and breakpoints (see: How to use the Debugger, Using Breakpoints).

Genetic algorithm - clustering points on screen

Below is the code I wrote for clustering using genetic algorithm. Points are from a picturebox, generated randomly (X,Y) before calling this class. However, the result of this algorithm is much worse than k-means or lbg I'm comparing it to. Can someone take a look for any errors in the algorithm, maybe I omitted something. Thanks.
I did this using arrays, the 2 other I did using lists, but I don't think that should have any impact on result.
public class geneticAlgorithm
{
static int pom = 0;
static PictureBox pb1;
public geneticAlgorithm(PictureBox pb)
{
pb1 = pb;
}
public static void doGA(PointCollection points, int clusterCounter)
//points is a list of points,
//those point have (X,Y) coordinates generated randomly from pictureBox
//coordinates. clusterCounter is how many clusters I want to divide the points into
{
//this part converts list of points into array testtab,
//where each array field hold X,Y of a point
Point[] test = new Point[points.Count];
test = points.ToArray();
double[][] testtab = new double[test.Length][];
for (int i = 0; i < testtab.GetLength(0); i++)
{
testtab[i] = new double[2];
testtab[i][0] = test[i].X;
testtab[i][1] = test[i].Y;
}
//end of converting
int n = testtab.GetLength(0);
int k = clusterCounter;
int chromosomeCount = 500;
int dimensions = 2;
double[][] testClusters = new double[k][];
for (int i = 0; i < k; i++)
{
testClusters[i] = new double[dimensions];
}
double[][] testChromosomes = new double[chromosomeCount][];
for (int i = 0; i < chromosomeCount; i++)
{
testChromosomes[i] = new double[2 * k];
}
int[][] testChromosomesInt = new int[chromosomeCount][];
for (int i = 0; i < chromosomeCount; i++)
{
testChromosomesInt[i] = new int[2 * k];
}
double[] partner = new double[chromosomeCount];
double[][] roulette = new double[chromosomeCount][];
for (int i = 0; i < chromosomeCount; i++)
{
roulette[i] = new double[1];
}
double[][] errors = new double[chromosomeCount][];
for (int i = 0; i < chromosomeCount; i++)
{
errors[i] = new double[1];
}
double crossingPossibility = 0.01;
double mutationPossibility = 0.0001;
int maxIterations = 10000;
//here I create chromosomes and initial clusters
for (int j = 0; j < chromosomeCount; j++)
{
for (int i = 0; i < k; i++)
{
Random rnd = new Random();
int r = rnd.Next(n);
for (int q = 0; q < dimensions; q++)
{
testClusters[i][q] = testtab[r][q];
}
}
int help = 0;
for (int i = 0; i < k; i++)
for (int l = 0; l < dimensions; l++) // here is creation of chromosome
{
testChromosomes[j][help] = testClusters[i][l];
help++;
}
//end
//here I call accomodation function to see which of them are good
errors[j][0] = accomodationFunction(testClusters, testtab, n, k);
//end
//cleaning of the cluster table
testClusters = new double[k][];
for (int i = 0; i < k; i++)
{
testClusters[i] = new double[dimensions];
}
}
//end
for (int counter = 0; counter < maxIterations; counter++)
{
//start of the roulette
double s = 0.0;
for (int i = 0; i < chromosomeCount; i++)
s += errors[i][0];
for (int i = 0; i < chromosomeCount; i++)
errors[i][0] = chromosomeCount * errors[i][0] / s;
int idx = 0;
for (int i = 0; i < chromosomeCount; i++)
for (int j = 0; i < errors[i][0] && idx < chromosomeCount; j++)
{
roulette[idx++][0] = i;
}
double[][] newTab = new double[chromosomeCount][];
for (int i = 0; i < chromosomeCount; i++)
{
newTab[i] = new double[2 * k];
}
Random rnd = new Random();
for (int i = 0; i < chromosomeCount; i++)
{
int q = rnd.Next(chromosomeCount);
newTab[i] = testChromosomes[(int)roulette[q][0]];
}
testChromosomes = newTab;
//end of roulette
//start of crossing chromosomes
for (int i = 0; i < chromosomeCount; i++)
partner[i] = (rnd.NextDouble() < crossingPossibility + 1) ? rnd.Next(chromosomeCount) : -1;
for (int i = 0; i < chromosomeCount; i++)
if (partner[i] != -1)
testChromosomes[i] = crossing(testChromosomes[i], testChromosomes[(int)partner[i]], rnd.Next(2 * k), k);
//end of crossing
//converting double to int
for (int i = 0; i < chromosomeCount; i++)
for (int j = 0; j < 2 * k; j++)
testChromosomes[i][j] = (int)Math.Round(testChromosomes[i][j]);
//end of conversion
//start of mutation
for (int i = 0; i < chromosomeCount; i++)
if (rnd.NextDouble() < mutationPossibility + 1)
testChromosomesInt[i] = mutation(testChromosomesInt[i], rnd.Next(k * 2), rnd.Next(10));
//end of mutation
}
//painting of the found centre on the picture box
int centrum = max(errors, chromosomeCount);
Graphics g = pb1.CreateGraphics();
SolidBrush brush = new SolidBrush(Color.Red);
for (int i = 0; i < 2 * k - 1; i += 2)
{
g.FillRectangle(brush, testChromosomesInt[centrum][i], testChromosomesInt[centrum][i + 1], 20, 20);
}
return;
}
//end of painting
public static int max(double[][] tab, int chromosomeCount)
{
double max = 0;
int k = 0;
for (int i = 0; i < chromosomeCount; i++)
{
if (max < tab[i][0])
{
max = tab[i][0];
k = i;
}
}
return k;
}
public static int[] mutation(int[] tab, int elem, int bit)
{
int mask = 1;
mask <<= bit;
tab[elem] = tab[elem] ^ mask;
return tab;
}
public static double[] crossing(double[] tab, double[] tab2, int p, int k)
{
double[] hold = new double[2 * k];
for (int i = 0; i < p; i++)
hold[i] = tab[i];
for (int i = p; i < 2 * k; i++)
hold[i] = tab2[i];
return hold;
}
//accomodation function, checks to which centre which point belongs based on distance
private static double accomodationFunction(double[][] klastry, double[][] testtab, int n, int k)
{
double Error = 0;
for (int i = 0; i < n; i++)
{
double min = 0;
int ktory = 0;
for (int j = 0; j < k; j++)
{
double dist = distance(klastry[j], testtab[i]);
if (j == 0)
{
min = dist;
}
if (min > dist)
{
min = dist;
ktory = j;
}
}
Error += min;
}
pom++;
return 1 / Error;
}
public static double distance(double[] tab, double[] tab2)
{
double dist = 0.0;
for (int i = 0; i < tab.GetLength(0); i++)
dist += Math.Pow(tab[i] - tab2[i], 2);
return dist;
}
}
The algorithm should work like so: (excuse me if not the best english)
1. Get random points (let's say 100)
2. Check into how many clusters we want to split them (the same thing I would do using k-means for example
3. Get starting population of chromosomes
4. Throu cutting on the roulette, crossing and mutation pick the best x centres, where x is the amount of clusters we want
5. Paint them.
Here are some results, and why I think it's wrong: (it's using 100 points, 5 clusters)
k-means:
lbg:
genetic(without colors now):
I hope this clarifies a bit.

Converting Codility solution to C# (Grocery-store, Hydrogenium 2013)

In order to learn and understand how Dijkstra's algorithm is used to solve the "Grocery Store" ([Hydrogenium 2013]: https://codility.com/programmers/challenges/hydrogenium2013) problem on codility, I'm trying to rewrite the #2, O(n^2) solution(https://codility.com/media/train/solution-grocery-store.pdf) in C#.
1) What language are those solutions written in?
2) What would be the C# equivalent to this bit of code?
G = [[]] *N
for i in xrange(M):
G[A[i]] = G[A[i]] + [(B[i], C[i])]
G[B[i]] = G[B[i]] + [(A[i], C[i])]
This is what I have so far
int[] G = new int[N];
for (int i = 0; i < M; i++)
{
G[A[i]] = G[A[i]];
G[B[i]] = G[B[i]];
}
Thanks in advance,
Gregory
Downloaded IDLE (a python IDE...kind of) and figured it out. It appears to be adding pairs to each array element. Here's the code I came up with if anyone else happens to stumble across the same problem.
private struct nodePair
{
public int node;
public int time;
public nodePair(int node, int time)
{
this.node = node;
this.time = time;
}
}
public int solution(int[] A, int[] B, int[] C, int[] D)
{
int M = A.Length;
int N = D.Length;
//build the graph
List<nodePair>[] G = new List<nodePair>[N];
for (int i = 0; i < N; i++)
{
G[i] = new List<nodePair>();
}
for (int i = 0; i < M; i++)
{
G[A[i]].Add(new nodePair(B[i], C[i]));
G[B[i]].Add(new nodePair(A[i], C[i]));
}
//initialize the distance table
int[] dist = new int[N];
for (int i = 0; i < N; i++)
{
dist[i] = int.MaxValue;
}
bool[] visited = new bool[N];
for (int i = 0; i < N; i++)
{
visited[i] = false;
}
//look for the minimum value
int ii = 0; ;
dist[0] = 0;
for (int k = 0; k < N; k++)
{
int s = int.MaxValue;
//find the minimum
for (int j = 0; j < N; j++)
{
if ((dist[j] < s) && (visited[j] == false))
{
s = dist[j];
ii = j;
}
}
visited[ii] = true;
if (s < D[ii])
{
return s;
}
List<nodePair> thisNodeLIst = G[ii];
foreach (nodePair oneNode in thisNodeLIst)
{
dist[oneNode.node] = Math.Min(dist[oneNode.node], s + oneNode.time);
}
}//for
return -1;
}
}

Categories

Resources