[英]Generate Random Numbers excluding a certain range of values- C#
I have 4 batches:我有4批:
10000-30000
30001-50000
50001-70000
71000-99999
I have to generate 500 random numbers for the followings groups excluding the values from {70000-71000}
我必须为以下组生成 500 个随机数,不包括
{70000-71000}
中的值
My code is somewhat like this.我的代码有点像这样。 My datagrid shows 500 records but it has numbers between {70-71k}.I need to calculate the count which is not giving me the required "500" count because certain random numbers are getting generated between {70-71k} which i need to exclude.
我的数据网格显示 500 条记录,但它的数字在 {70-71k} 之间。我需要计算没有给我所需的“500”计数的计数,因为我需要在 {70-71k}排除。
int i=10000, j=99999;
int batch1Count = 0, batch2Count = 0, batch3Count = 0, batch4Count = 0;
private void button1_Click(object sender, EventArgs e)
{
try
{
this.dataGridView1.Rows.Clear();
string prefix = comboBox1.SelectedValue.ToString();
switch (prefix)
{
case "1": prefix = "USN"; break;
case "2": prefix = "DOT"; break;
case "3": prefix = "USAF"; break;
case "4": prefix = "COV"; break;
}
for (int k = 0; k < 500; k++)
{
Random random = new Random(DateTime.UtcNow.Millisecond);
//Generate random values
int result = random.Next(i,j);
Thread.Sleep(1);
if (result >= 70000 && result <= 71000)
{
k=k-1;
}
else
{
//Add prefix to the generated random value
string key = prefix + result;
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dataGridView1);
row.Cells[0].Value = key;
this.dataGridView1.Rows.Add(row);
Thread.Sleep(3);
if (result >= 10000 && result <= 30000)
{
Thread.Sleep(1);
batch1Count++;
}
else if (result >= 30000 && result <= 50000)
{
Thread.Sleep(1);
batch2Count++;
}
else if (result >= 50000 && result <= 70000)
{
Thread.Sleep(1);
batch3Count++;
}
else if (result >= 71000 && result <= 99999)
{
Thread.Sleep(1);
batch4Count++;
}
}
}
}
catch (Exception ex)
{ }
}
Can't you just use the Random class for it?你不能只使用Random类吗?
The Random
class has a Next(int, int)
method that generates a random number between the specified values. Random
类有一个Next(int, int)
方法,可以在指定值之间生成一个随机数。 You could simply generate one and if it is in the {70k-71k} range, generate another one.您可以简单地生成一个,如果它在 {70k-71k} 范围内,则生成另一个。
Rather than throwing out numbers that are in the range 70000-71000, generate a number from 10000-89999 and if it's greater than 70000 then add 1000 to it.与其丢弃 70000-71000 范围内的数字,不如从 10000-89999 生成一个数字,如果它大于 70000,则向其添加 1000。 For example:
例如:
var num = rnd.Next(10000, 90000);
if (num > 70000)
{
num += 1000;
}
You're just mapping the numbers in the range 70001-89999 to 71001-99999.您只是将 70001-89999 范围内的数字映射到 71001-99999。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.