MAB
MAB

Reputation: 273

Generating random numbers from giving numbers in c#

User enters numbers to 10 textbox and i sent them to an array. Now i want to generate random numbers from this array. What can i do?

Upvotes: 0

Views: 277

Answers (2)

vgru
vgru

Reputation: 51322

Something like this:

public class Randomizer<T>
{
    private readonly Random _random = new Random();
    private readonly IList<T> _numbers;
    public Randomizer(IList<T> numbers)
    {
        _numbers = numbers;
    }

    public T Next()
    {
        int idx = _random.Next(0, _numbers.Count);
        return _numbers[idx];
    }
}

Usage:

var r = new Randomizer<int>(new int[] { 10, 20, 30, 40, 50 });
for (int i = 0; i < 100; i++)
     Console.Write(r.Next() + " ");

Or do you want to shuffle the array?

[Edit]

To shuffle the array, you can use the Fisher–Yates shuffle shown in this post:

// https://stackoverflow.com/questions/108819/110570#110570
public class Shuffler
{
    private Random rnd = new Random();
    public void Shuffle<T>(IList<T> array)
    {
        int n = array.Count;
        while (n > 1)
        {
            int k = rnd.Next(n);
            n--;
            T temp = array[n];
            array[n] = array[k];
            array[k] = temp;
        }
    }
}

If you want the interface to be same as the Randomizer class above, you can modify it to use the Shuffler class:

public class Randomizer<T>
{
    private readonly Shuffler _shuffler = new Shuffler();
    private readonly IList<T> _numbers;
    public Randomizer(IList<T> numbers)
    {
        _numbers = new List<T>(numbers);
        _shuffler.Shuffle(_numbers);
    }

    volatile int idx = 0;
    public T Next()
    {
        if (idx >= _numbers.Count)
        {
            _shuffler.Shuffle(_numbers);
            idx = 0;
        }

        return _numbers[idx++];
    }
}

Note that the code is not thread safe, so some locking should be implemented if Next method might be called simultaneously from multiple threads.

Upvotes: 3

Vilx-
Vilx-

Reputation: 107072

Seed the standard System.Random class with a value from the array? If you need your random numbers to depend on ALL array items, then just XOR them all.

public static Random BuildSeededRandom(int[] data)
{
    if ( data == null || data.Length < 1 )
        return new Random();

    int xor = 0;
    foreach ( var i in data )
        xor ^= i;

    return new Random(xor);
}

Upvotes: 1

Related Questions