Search code examples
c#arraysrepeatfill

Array repeats one value


I have filled an array of this object and I think I'm filling it fine until I ask to repeat what I have just filled it with and see that they are all the same result. I know it's something simple but I'm missing it right now.

static void Main(string[] args)
{
    int numOFItems = 6;
    int population = 10;

    int[] geneList = new int[numOFItems];
    Genome[] gen = new Genome[population];
    Random rand = new Random();
    Genome gene;

    for (int i = 0; i < population; i++)
    {
        gen[i] = new Genome();
        for (int j = 0; j < numOFItems; j++)
        {
            geneList[j] = rand.Next(0, 4);
        }
        gene = new Genome(geneList);
        gen[i] = gene;
        Console.Out.Write("\n" + gen[i].ToString());
    }
    for (int i = 0; i < population; i++)
        Console.Out.Write("\n" + gen[i].ToString() + ";");
    Console.ReadLine();
}

class Genome
{
    int[] geneList;
    int numOFItems = 6;

    public Genome()
    {
        geneList = new int[numOFItems];
    }

    public Genome(int[] geneList)
    {
        this.geneList = geneList;
    }

    public int[] GeneList
    {
        get { return geneList; }
        set { geneList = value; }
    }

    public override string ToString()
    {
        return "" + GeneList[0] + GeneList[1] + GeneList[2] 
            + GeneList[3] + GeneList[4] + GeneList[5];
    }
}

Solution

  • You're only initializing geneList once - so each Genome contains a reference to the same array. Move your declaration and initialization of geneList inside the loop. Note that you're also creating a new Genome instance right at the start of the list, and overwriting it afterwards. So I think your loop ought to look like this:

    for (int i = 0; i < population; i++)
    {
        int[] geneList = new int[numOFItems];
        for (int j = 0; j < numOFItems; j++)
        {
            geneList[j] = rand.Next(0, 4);
        }
        gen[i] = new Genome(geneList);
    }