0

I have put together some code to generate multiple arrays of random numbers. The code generates a different array of random numbers every time, but when I try to write each new set of numbers to an individual text file each file has the same numbers written to them (those from the first array generated). Does anyone know how I can edit the code so that each file has a different array written to it? I'll add the code that shows how the numbers are generated if it helps.

for (int repeat = 0; repeat < 100; repeat++)
{   
    Random random = new Random();
    int[] randomNumbers = new int[50];
    int[] array = new int[6];

    //Generate array of random numbers

    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"c:\CodeFolder\repeat.ToString() + ".txt"))
    {
        foreach (int number in array)
        {
            file.WriteLine(number);
        }
    }
}

Edit: Sorry about that. Part of the code used in the first post was incorrectly typed. Anyway, I have edited the code so that now it works like this.

string fileName = repeat.ToString();

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"c:\CodeFolder\" + fileName + ".txt"))

This time around the first file has a unique array of numbers written to it, but every other file contains the same array. Not too sure what's going on with it.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
user3277234
  • 55
  • 3
  • 9
  • 2
    This is going to be a problem as well, I think: `System.IO.StreamWriter(@"c:\CodeFolder\repeat.ToString() + ".txt"))` should be `System.IO.StreamWriter(@"c:\CodeFolder\" + repeat.ToStrign() + ".txt"))` – Tim May 23 '14 at 16:46

2 Answers2

4

There are two problems with this code.

  1. The "ToString" call is inside the quoted area, so is a string literal (not a function call). This means you will only ever get one text file. You probably meant to write:

    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"c:\CodeFolder\" + repeat.ToString() + ".txt"))
    
  2. By recreating the Random object very quickly, you are not allowing the correct re-seeding to occur. You need to move it out of the for loop and into your function or class.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
1

Try putting your

Random random = new Random();

outside of the for loop. A Random creates a list of random values based of a seed. If the default seed were to be 0, recreating the Random variable each team would restart the same list of random numbers, thus always giving the same numbers.

Papsicle
  • 147
  • 11