Random randomSeed = new Random();
int seed = randomSeed.Next(255);
String display = "";
int min = 1;
int max = 10;
int number;
Random rand = new Random(seed);
for (int i = 0; i < max; i++)
{
number = rand.Next(min, max);
display += "\t" + number;
}
rtOutput.Text = display;
我正在尝试使用visual c#获得PRNG。 我遇到的问题是数字不断重复。 这是1随机的结果: 2 6 3 7 9 7 9 3 3 7
从结果来看,数字3,7,9正在重复。 任何想法我的错误代码在哪里? 任何使它不重复相同数字的解决方案?
`最后我得到了自己的PRNG,经过多次尝试,这是我的代码:
// Manually input the Seed, or you can make it random like my code above.
int seed = Convert.ToInt32(tbSeed.Text);
String display = "";
int min = 1;
// Max value is manually input, for how many number will be generated.
// i need to plus by 1 for the max value because i state the min value is 1.
int max = Convert.ToInt32(tbMax.Text) + 1;
Random rand = new Random(seed);
int number;
// this dictionary is for saving the number generated by random, if exist,
//do random again.
Dictionary<int, int> num = new Dictionary<int,int>();
for (int i = 1; i < max; i++)
{
number = rand.Next(min, max);
if (num.ContainsKey(number))
{
while (true)
{
number = rand.Next(min, max);
if (num.ContainsKey(number))
{ // if exist do nothing and then random again while true }
else
{
num.Add(number, 1);
break;
}
}
}
else
{
num.Add(number, 1);
}
display += "\t" + number;
}
// display the random number.
rtOutput.Text = display;
`
答案 0 :(得分:0)
你想要的是一个随机的&#34;有序的&#34;列表,而不是随机生成的#34;名单。这通常被称为&#34; Shuffling&#34;。
这里有一些示例代码(不是很好的代码,但我把它作为样本尽可能接近)来实现你想要的目标:
static void Shuffle(int[] list)
{
var rnd = new Random();
int n = list.Count();
while (n > 1)
{
n--;
int k = rnd.Next(n + 1);
int value = list[k];
list[k] = list[n];
list[n] = value;
}
}
static void Main(string[] args)
{
int min = 1;
int max = 10;
int [] numbers = new int[max-min];
for (int i = min; i < max; i++)
numbers[i-min] = i;
Shuffle(numbers);
string display = "";
for (int i = min; i < max; i++)
display += " " + numbers[i-min];
Console.Write(display);
}
结果应该是这样的:
4 9 2 1 3 7 5 8 6
适用于任何min
和max
值(生成的数字与中间值相同)
答案 1 :(得分:0)
// all the numbers we want to use (you could also generate this programmatically)
List<int> oneToTen = new List<int> {1,2,3,4,5,6,7,8,9,10};
String display = "";
int number;
Random rand = new Random();
for (int i = 0; i < 10; i++) {
int randomIndex = rand.Next(0, oneToTen.Count); // choose one at random
number = oneToTen[randomIndex];
oneToTen.Remove(number); // remove it so we don't choose it agian
display += "\t" + number;
}