korgan
korgan

Reputation: 43

Random number in loop

My function return the same number sequence. When i give on input list with first list[0] all 0 and second list[1] all 1, i get on the output list e.g:

1 1 1 1 0 1 1
1 1 1 1 0 1 1

And all the time generate sequence on the output is the same.

I mean temp[0] and temp[1] have the same sequence

public List<float[][][]> rozmnarzanie(List<nur> list,Random dnd)
{
    float[][][] ftemp=net.wagi;
    List<float[][][]> temp = new List<float[][][]>();

    for (int i = 0; i < 2; i++) 
    {
        for (int a = 0; a < net.wagi.Length; a++)
        {
            for (int j = 0; j < net.wagi[a].Length; j++)
            {
                for (int k = 0; k < net.wagi[a][j].Length; k++)
                {
                    if(dnd.Next(0,100)<=50)
                    { 
                        ftemp[a][j][k] = list[0].listawagi[a][j][k];
                    }
                    else
                    {
                        ftemp[a][j][k] = list[1].listawagi[a][j][k];
                    }
                }
            }
        }
        temp.Add(ftemp);
    }
    return temp;
}

Upvotes: 1

Views: 112

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273179

I mean temp[0] and temp[1] have the same sequence

Correct. You add the same array twice, temp[0] and temp[1] are both references to the same location in memory. What you see are the results of the last run. The same result will show up in net.wagi .

Your question isn't about random numbers but about arrays being reference types.

I don't know what net.wagi is but the solution could look something like:

//float[][][] ftemp=net.wagi;
List<float[][][]> temp = new List<float[][][]>();
for (int i = 0; i < 2; i++) 
{
   float[][][] ftemp = new float[a][b][c];  // pseudo code

   ... 

   temp.Add(ftemp);
 }

You figure out the a, b and c.

Upvotes: 2

Related Questions