【发布时间】:2017-08-07 05:46:51
【问题描述】:
参考generating random numbers without consecutive repetition,我想做一个不重复的随机整数生成器,但在2到9之间。
我充分利用了上述网址中答案的包装代码。
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 像一个模式一样重复,而在另一个序列中,您会看到所有四个 9。
【问题讨论】:
-
不知道你为什么要在每个循环中执行 4 个
newrands - 但如果你真的想在每个循环中创建 4 个样本,你应该在每个循环之间重新生成adder- 否则,你没有正确地遵循模式。 -
多久生成一次这个结果?