Ссылаясь на генерацию случайных чисел без последовательного повторения, я хочу сделать не- повторяющийся генератор случайных целых чисел, но от 2 до 9 включительно.
Я хорошо использую код упаковки из ответа в приведенном выше URL-адресе.
int oldrand = <prior random number>;
int adder = randomNumberGenerator() % 4;
int newrand = (oldrand + adder + 1) % 5;
Мой код, однако,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
Random Rand = new Random();
int oldrand = Rand.Next(0,7);
//Console.WriteLine(oldrand);
for (int i=0; i<50;i++) {
int adder = Rand.Next(0,7) % 7;
int newrand = (oldrand + adder + 1) % 8+2;
int newrand2 = (newrand + adder + 1) % 8+2;
int newrand3 = (newrand2 + adder + 1) % 8+2;
int newrand4 = (newrand3 + adder + 1) % 8+2;
Console.WriteLine(newrand);
Console.WriteLine(newrand2);
Console.WriteLine(newrand3);
Console.WriteLine(newrand4);
oldrand = newrand4;
Console.WriteLine();
}
}
}
public class Rand {
private static readonly Random globalRandom = new Random();
private static readonly object globalLock = new object();
private static readonly ThreadLocal<Random> threadRandom = new ThreadLocal<Random>(NewRandom);
public static Random NewRandom()
{
lock (globalLock)
{
return new Random(globalRandom.Next());
}
}
public static Random Instance { get { return threadRandom.Value; } }
public static int Next(int minValue, int maxValue)
{
return Instance.Next(minValue, maxValue);
}
}
}
выдает странный результат:
2
7
4
9
2
3
4
5
2
7
4
9
5
9
5
9
8
7
6
5
3
9
7
5
2
7
4
9
5
9
5
9
5
9
5
9
9
9
9
9
5
9
5
9
7
5
3
9
8
7
6
5
3
9
7
5
9
5
9
5
4
3
2
9
6
3
8
5
2
7
4
9
6
3
8
5
9
5
9
5
Как вы можете видеть, 5 и 9 повторяются как шаблон, в то время как в другой последовательности вы видите все четыре девятки.