sydluce sydluce - 3 months ago 7
C# Question

Loop not running when its method to run it is called

If I call the default constructor "Creature" in main and then try to call the method "Generate Creator" the loop never runs. If I did a normal for loop it throws out of bounds errors even knowing the default constructor sets the length of the array. It is probably a dumb error I am not seeing. (this isnt all of the code)

class Creature
{
static int geneLength;
byte[] Chromosome = new byte[geneLength];
int fitness;

string geneString;
Random rn = new Random();

public Creature()
{
geneLength = 36;
fitness = 0;
}

public void GenerateCreature()
{
foreach(byte g in Chromosome)
{
Chromosome[g] = (byte)rn.Next(0, 2);
geneString += Chromosome[g].ToString();
}
}
}


Main:

namespace Creature_Generator
{
class Program
{
static void Main(string[] args)
{
Creature c = new Creature();

c.GenerateCreature();
Console.WriteLine(c.getGeneString);

}
}
}

Answer
foreach(byte g in Chromosome)
{
    Chromosome[g] = (byte)rn.Next(0, 2); // 'g' is not an index
    geneString += Chromosome[g].ToString(); // 'g' is not an index
}

while you are using foreach (byte g in Chromosome), I believe it is not a proper way to use code like Chromosome[g] which g is suppose a value not an index

try

StringBuilder geneString = new StringBuilder();
public Creature()
{
    geneLength = 36;
    this.Chromosome = new byte[geneLength];
    fitness = 0;
}

for (int i = 0; i < this.Chromosome.Length; i++)
{
    byte g = this.Chromosome[i]; // this line is useless
    this.Chromosome[i] = (byte)rn.Next(0, 2);
    geneString.Append(this.Chromosome[i].ToString());
}

Plus, if you are hard-coding geneLength = 36 in the constructor, consider use public int geneString { get; private set;} instead of static int geneLength; or

static int _geneLength = 36;
public int geneLength { get; private set; }

public Creature() { this.geneLength = _geneLength; }
public Creature(int geneLength) { this.geneLength = geneLength; }

Edit 1 -

According to @moreON advice, string geneString is modified from class string to StringBuilder, read more on https://msdn.microsoft.com/en-us/library/system.text.stringbuilder(v=vs.110).aspx

Comments