3

// Create a string array that consists of ten lines. string[] personalNumbers; // declare personalNumbers as a 10-element array personalNumbers = new string[10]; //= { "First number", "Second number", "Third line", etc}

        for (int i = 0; i < 9; i++)   // populate the array  with 10 random values
        {
            Random random = new Random();
            int randomNumber = random.Next(1, 50);

            string RandomNumberText = Convert.ToString(randomNumber);

            personalNumbers[i] = RandomNumberText;   
        }

Hi, I know that this SEEMS to be a duplicate of previously asked questions, but I am trying to generate a series of random numbers between 1 and 50 to populate an array

The problem is, if I do it as we were taught in class, each number is the same

I know that the problem is that the tight loop causes the random to be seeded with the same number

What NONE of the other threads addresses however, is HOW to fix this problem when using a loop iteration....

All of the explanations thus far are so far advanced beyond our level that I (and the other askers BTW) have no clue how to implement them as a solution, which I also cannot submit in class as they are techniques that we have not covered

The tutorials at Microsoft insist that putting the random inside the loop is the right solution

I've tried putting an instance of random outside the loop and then calling it from inside the loop but this has caused an exception

Is there a straightforward way to use random to create a series of random numbers that doesn't run into this problem?

Mike Marini
  • 43
  • 1
  • 1
  • 4
  • 2
    If you look at the related column on the right you could find your answer. No, do not put the random inside the loop – Steve Nov 03 '13 at 22:09
  • It is what it seems, random should be initialized once.. – Yosi Dahari Nov 03 '13 at 22:11
  • 1
    "I've tried putting an instance of random outside the loop and then calling it from inside the loop but this has caused an exception". So you have tried to implement the correct solution, "it did not work". Could you share som emore information with us about that exception, maybe show us the code? Because it sounds like that actually should be the solution :) – oerkelens Nov 03 '13 at 22:43
  • 1
    "The tutorials at Microsoft insist that putting the random inside the loop is the right solution" What tutorials? – Preston Guillot Nov 03 '13 at 22:55
  • Actually, the above program will generate different number on Unix family. It will generate the same value on Windows. To solve this issue on Windows, just put the new Random outside the loop. – Freelancer Sep 08 '22 at 00:28

4 Answers4

6

Create the random instance outside of the loop:

Random random = new Random();
for (int i = 0; i < 9; i++)   // populate the array  with 10 random values
{

MSDN:

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
4

You have to define the Random object outside the loop and just get a number each time inside the loop. If you create it each time again, it will be created with the same initial value because the interval between creations is too small.

Random random = new Random();

for (int i = 0; i < 9; i++) {
 int randomNumber = random.Next(1, 50);
} 
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
1

I've tried putting an instance of random outside the loop and then calling it from inside the loop but this has caused an exception

Here are two concrete examples, one for a Console app, and the other for a WinForms app.

This is one way to declare it in a Console app. random can be used from anywhere within the application, even in methods other than Main():

class Program
{

    private static Random random = new Random();

    static void Main(string[] args)
    {
        // ... code ...

        for (int i = 0; i < 9; i++)   // populate the array  with 10 random values
        {
            int randomNumber = random.Next(1, 50);

            personalNumbers[i] = randomNumber.ToString();
        }

        // ... code ...
    }

}

This is one way to declare it for use in a WinForms app. random in this example can be used anywhere within Form1:

public partial class Form1 : Form
{

    private Random random = new Random();

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // ... code ...

        for (int i = 0; i < 9; i++)   // populate the array  with 10 random values
        {
            int randomNumber = random.Next(1, 50);

            personalNumbers[i] = randomNumber.ToString();
        }

        // ... code ...
    }

}

This should cover most simple homework assignments. Nothing fancy here.

Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • Thank you Idle_Mind... that was far more simple and elegant than I had hoped for...I was afraid to do that as it seemed that using random.Next(1, 50) would generate the same repetitive numbers Am I right in understanding that the external instance of random is the part that is actually GENERATING the random number and the random.Next inside the loop is simply FETCHING that value (or calling it, I suppose)? – Mike Marini Nov 04 '13 at 00:01
  • That's correct!...you got it. – Idle_Mind Nov 04 '13 at 00:12
0

thank you for the input, it is much appreciated!

I have posted the complete code thus far, which is now giving me what seems like "random" numbers in that they are always different when I run it

@Steve thank you...I have looked at those questions, but all of the solutions involve using some other technique than random() which I am not allowed to use

@Oerkelens thank you, when I moved the code for random() outside the loop, I got two possible results one was a series of 9, 9-digit random numbers, or an exception that says

Error 1 A local variable named 'randomNumber' cannot be declared in this scope because it would give a different meaning to'randomNumber', which is already used in a 'parent or current' scope to denote something else

I have posted the larger bit of code to show what I have changed to get it to work...I don't really understand how to properly call the random() from within the loop, but for some reason, having the same line both inside and outside of the loop did the trick

@Preston - we don't have a textbook for this course, and we are only allowed to use techniques that are contained within the Microsoft C# video tutorials by Bob Tabor (learnvisualstudiodotnet) and Envato (learn C# in 30 days)

I apologize if this all seems obvious to you, but we are in the position of being told that half-way through the course that we are switching from learning to program in Visual Basic to C#, so all of our work now needs to be re-written in C#, without any particular instruction in how to how to use this language...needless to say, it is a huge stress and we are being left without any resources to do this, so much of what we are doing is guesswork

the more complete code that is "working"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace GuessingGameProgram
{
class Program
{
    int randNum;
    static void Main(string[] args)
    {
        // Create a string array that consists of ten lines. 
        string[] personalNumbers; // declare personalNumbers as a 10-element array 
        personalNumbers = new string[10];  //= { "First number", "Second number", "Third line",   etc}

        Random outsideLoopRandom = new Random();
        int randomNumber = outsideLoopRandom.Next(1, 50);


        for (int i = 0; i < 9; i++)   // populate the array  with 10 random values
        {
            randomNumber = outsideLoopRandom.Next(1, 50);
            string RandomNumberText = Convert.ToString(randomNumber);

            personalNumbers[i] = RandomNumberText;   
        }

        // WriteAllLines creates a file, writes a collection of strings to the file, 
        // and then closes the file.
        //System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);



        foreach (string i in personalNumbers) // this is just a test to see what the output is
        {
            Console.Write("{0} ", i);
        }


        Console.ReadLine();



    }
}

}

        //randNum = Random.Equals(1, 50);



        //StreamReader myReader = new StreamReader("personalNumbers.txt");
        //string line = "";
        //while (line != null)
        //{
        //    line = myReader.ReadLine();
        //    if (line != null)
        //        Console.WriteLine(line);
        //}

        //myReader.Close();
        //Console.ReadLine();

        //personalNumbers = RandomNumbers.next(1, 10);

        //int returnValue = personalNumbers.Next(1, 50);

        //int Guess = 0;

        //Console.WriteLine("Please guess a number between 1 and 50");
        //Console.ReadLine();
        ////while (Guess = Convert.ToInt32(Console.Read());

        //if (Guess < returnValue)
        //{
        //    Console.WriteLine("Wrong! the number that I am thinking of is higher than " + Guess + ". Try again!");
        //    Console.ReadLine();
        //}

        //if (Guess > returnValue)
        //{
        //    Console.WriteLine("Wrong! The number that I am thinking of is lower than " + Guess + ". Try again!");
        //    Console.ReadLine();
        //}
        //        else if (Guess = returnValue)
        //        Console.WriteLine("Correct! The number that I was thinking of was " + Guess + ". Congratulations!");
    //    //{
    //Console.WriteLine("Let's play a guessing game!")
    //Console.WriteLine("")
    //Console.WriteLine("guess a number between 1 and 10")
    //Console.WriteLine("")



    //randNum = randomGenerator.Next(1, 10)


    //While userGuess <> randNum
    //    {

    //    userGuess = Console.ReadLine()
    //    }
    //    If userGuess > randNum Then
    //        Console.WriteLine("too high, guess again!")
    //    {
    //   If userGuess < randNum Then
    //        Console.WriteLine("too low, guess again!")
    //    }
    //   Else


    //End While

    //Console.WriteLine("Correct! the secret number is " & randNum)
    //Console.ReadLine()
Mike Marini
  • 43
  • 1
  • 1
  • 4