简体   繁体   中英

Array 2 method random generated number

For a part of a program i need the following 2 methods.

The first method listed will generated a random number. where the 2nd method will "call" this method to fill the array.

The array has a max. number of elements defefined on 100 (and all the random generated numbers should be between 1-100).

The problem is i never get random numbers generated. (either i get 100 x the same value, 3 random numbers divided over the 100 max. elements of the array, or the same value 100 times all over again).

The problem should be in the first method, but i cannot seem to figure out the problem. Been staring at this for quite some time now...

The problem should be with the return, cause it DOES create random generated numbers. But how do i return the generated value every time? (the int method has to be called with the 3 parameters).

        private int ValidNumber(int[] T, int X, int Range)
    {
        for (byte I = 0; I < T.Lenght; I++)
        {
            Random RndInt = new Random();
            X = RndInt.Next(1, Range+1);
        }
        return X; 

    }/*ValidNumber*/


  public void FillArray(int[] T, int Range)
    {
        for (byte I = 0; I < T.Length; I++)
        {
            T[I] = ValidNumber(T, I, Range);
        }

    }/*FillArray*/

Console code:

public void ExecuteProgram()
    {
        ClsBereken Ber = new ClsBereken();

        //const byte Range = 100;
        const int Max = 100;
        int[] T = new int[Max];

        Ber.FillArray(T, Max);
        DisplayArray(T);

    }/*ExecuteProgram*/

    private void DisplayArray(int[] T)
    {
        for (byte i = 0; i < T.Length; i++)
        {
            Console.Write("{0,4} ", T[i]);
        }
        Console.WriteLine();
    }/*DisplayArray*/

Any help alot appreciated. Kind Regards.

Re-use the Random instance. NOTE I've edited this to show passing the Random instance down, but I'm really not sure what ValidNumber is trying to do - it looks like it is juts burning up CPU cycles? I would suggest you can remove ValidNumber completely (and just use the next value from the Random in FillArray ), but presumably you are trying to do something here - I'm just not sure what!

private int ValidNumber(int[] T, int X, int Range, Random random)
{
    for (byte I = 0; I < T.Lenght; I++)
    {
        X = random.Next(1, Range+1);
    }
    return X; 

}/*ValidNumber*/


public void FillArray(int[] T, int Range)
{
    Random random = new Random();
    for (byte I = 0; I < T.Length; I++)
    {
        T[I] = ValidNumber(T, I, Range, random);
    }

}/*FillArray*/

When you create a Random , it is "seeded" using the system clock, but this is rounded heavily. If you create lots of Random in a tight loop, they all get the same "seed", so they all create the same next number.

If necessary you could move the Random further out (if you have other loops), or make it static (but if you do that you need to worry about synchronization too).

The problem is that you are reinitializing rndint over and over.

take the line:

Random RndInt = new Random();

and move it in front of the loop and see if that fixes it.

When you initialize a random object, it is assigned a seed (probably based on the time), and that seed is used to generate a series of seemingly random values. However, if you plug in the same seed to two random objects, you will get the same series of random numbers.

So, what is happening in your code is you are initializing a new random object with a seed, and then asking for the first random number in its series. Then, you are initializing another random object (even though it is assigned to the same name, it is a new object) and it is getting the same seed, and you are again asking for the first random number in the series. So naturally, you are getting the same random number over and over.

You are continuously creating an new Random object. I'm afraid this is seeded (randomized) by the timestamp of creation. Since this is really fast and happens multiple times, the seed is the same, and so is the result of the call RndInt.Next(1, Range+1); .

By the way, even though not incorrect, it's not a common practice in c#.net to start with a capital letter on names of local variables and parameters.

Any random number generation algorithm* is not truly random; it is simply a deterministic algorithm that has been specifically designed to output numbers that resemble randomness. (See Pseudorandom number generator .) Since the algorithm is deterministic, its output is completely dependent upon a starting "seed" value.

The Random class in .NET has two constructors: one which takes an integer seed, and another which takes no parameters. This one bases its seed off the current time.

From this information perhaps you can guess why creating a new Random instance for every value in your array results in the entire array being filled with the same number: every time you construct a Random object within a very small time frame , it will have the same seed value, which means it will generate identical output to another Random object constructed within the same time frame.

As Marc Gravell has already indicated, you should be using only a single Random instance to generate a sequence of random numbers.

*Well, almost any. I believe there are hardware implementations of random number generators that factor in random noise (taken from the surrounding environment) and may therefore be considered "truly" random. Whether you believe these are actually random depends on your personal definition of "random" and whether or not you believe that we live in a deterministic universe.

You can pass Random() a seed but if you send it the same seed number you will get the same results. The way you are using it

Random rnd = new Random();

Is using an auto-generated seed based on time. But you may not get seemingly random results if you don't at least sleep for a second. (Source http://msdn.microsoft.com/en-us/library/system.random(VS.71).aspx )

As everyone has mentioned here already your biggest issue is the fact you keep recreating the random object each iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM