C# Random

By FoxLearn 12/14/2024 2:11:37 PM   165
In C#, the Random class is used to generate random numbers.

The Random class in C# represents a pseudo-random number generator, which uses an algorithm to produce a sequence of numbers that appear random but are actually determined by an initial value (the "seed"). These numbers meet certain statistical criteria for randomness, making them suitable for simulations, games, and other applications where randomness is needed, though they are not truly random, as they are algorithmically generated.

C# random numbers

In this example, random numbers are generated using the Random class to demonstrate how to produce various types of random values.

using System;

class Program
{
    static void Main()
    {
        var rand = new Random();        
        // Generate a random double between 0.0 and 1.0
        Console.WriteLine(rand.NextDouble());

        // Generate a random Int64 (long)
        Console.WriteLine(rand.NextInt64());

        // Generate random bytes and fill the byte array
        var buffers = new byte[8];
        rand.NextBytes(buffers);

        // Print byte array
        Console.WriteLine(string.Join(" ", buffers));
    }
}

Output:

0.367474761496985
5274873010621668023
49 95 180 119 129 134 115 75

C# random Next

The Next method returns a random integer, and we can specify both lower and upper limits for the generated random numbers by providing two arguments: the minimum and the maximum values.

var rand = new Random();
Console.WriteLine(rand.Next()); // Generate a random integer between 0 and Int32.MaxValue
Console.WriteLine(rand.Next(7)); // Generate a random integer between 0 and 7 (exclusive):
Console.WriteLine(rand.Next(11, 25)); //Generate a random integer between 11 (inclusive) and 25 (exclusive):

Output:

752804242
4
15

C# pick random element

To pick a random element from a collection (such as an array, list, or any other enumerable), you can use the Random class along with the Next method to generate a random index within the valid range of the collection.

using System;

class Program
{
    static void Main()
    {
        var rand = new Random();
        int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        // Pick a random index and use it to select a random element
        int index = rand.Next(numbers.Length);
        Console.WriteLine("Random Element: " + numbers[index]);
    }
}

C# shuffle list

You can shuffle a list (or any collection) by randomizing the order of its elements.

using System;
using System.Collections.Generic;

class Program
{
    static Random rand = new Random();

    static void Main()
    {
        // Correct List initialization
        List<int> vals = new List<int> { 1, 2, 3, 4, 5, 6 };
        List<string> words = new List<string> { "c#", "c++", "c", "java", "javascript" };
        // Shuffle both lists
        Shuffle(vals);
        Shuffle(words);

        // Print shuffled vals
        foreach (var e in vals)
            Console.Write($"{e} ");

        // Print shuffled words
        foreach (var e in words)
            Console.Write($"{e} ");
        Console.ReadLine();
    }

    // Fisher-Yates shuffle method
    static void Shuffle<T>(IList<T> vals)
    {
        int n = vals.Count;
        // Shuffle elements in-place using Fisher-Yates algorithm
        while (n > 1)
        {
            n--;
            int k = rand.Next(n + 1);  // Generate random index
            // Swap elements
            (vals[n], vals[k]) = (vals[k], vals[n]);
        }
    }
}

If you're using .NET 6 or later, you can use Random.Shared for better performance and thread-safety.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        // Shuffle using Random.Shared
        var shuffledList = numbers.OrderBy(x => Random.Shared.Next()).ToList();
        // Print the shuffled list
        Console.WriteLine("Shuffled List: " + string.Join(", ", shuffledList));
    }
}

Fisher-Yates Shuffle is the most efficient in-place algorithm for shuffling a list in C#. It ensures that each element has an equal chance of being placed in any position.