How to write a linear congruent generator (LCG) in C #? Or are there any well-known implementations?

I want to create a random array of sequences that repeat and use only one number of times. For example, given a range of 0-9 with two different seeds, you can get

Seed 1: 7 3 5 9 0 8 1 2 6 4 | 7 3 5 9 0 8 1 2 6 4 | 7 3 5 9 0 8 1 2 6 4
Seed 2: 2 5 7 1 4 9 6 8 3 0 | 2 5 7 1 4 9 6 8 3 0 | 2 5 7 1 4 9 6 8 3 0

From what I understand, a linear congruent random number generator or LCRNG or LCG can give me this http://en.wikipedia.org/wiki/Linear_congruential_generator

Any idea if the implementation exists in C # or how I will start writing it.

How does Twers differ from Mersenne from LCG?

Not sure if all my questions have been answered, but here is what I used. Since I limit the sample size to a range of values ​​from max to min, I choose another prime number that remains static as long as the same seed is given. I do this because I want the same sequence to give the same seed and the same min / max boundaries for repeatability testing.

Please criticize everything I do here is what I came up with in an instant:

using System;
using System.Collections.Generic;

namespace FULLCYCLE
{
    public class RandomNumber
    {
        private int _value;
        private int _prime;
        private static List<int> primes = new List<int>()
        {
            11,
            23,
            47,
            97,
            797,
            1597,
            6421,
            25717,
            51437,
            102877,
            411527,
            823117,
            1646237,
            3292489,
            6584983,
            13169977,
            26339969,
            52679969,
            105359939,
            210719881,
            421439783,
            842879579,
            1685759167
        };

        public RandomNumber( int seed )
        {
            _prime = primes[seed%primes.Count];
            _value = seed;
        }

        public int Next( int min, int max )
        {
            int maxrate = (max-min+1);
            if (_value > maxrate)
            {
                _value = _value % maxrate;
            }

            _value = (_value + _prime) % maxrate;
            return _value + min;
        }
    }
}
+3
source share
2 answers

Why not just use the existing class Randomand Knuth shuffle in your input sequence?

+1
source

, LCG ...

  • :

    // generates 3, 4, 5, 6, 7, 8, 9, 0, 1, 2
    var rng = new RandomNumber(42);
    for (int i = 0; i < 10; i++) Console.WriteLine(rng.Next(0, 9));
    
  • :

    // generates 579, 579, 579, 579, 579, 579, 579, 579, 579, 579
    var rng = new RandomNumber(123);
    for (int i = 0; i < 10; i++) Console.WriteLine(rng.Next(456, 51892));
    

seed/min/max, .

+1

Source: https://habr.com/ru/post/1769576/


All Articles