private void button1_Click(object sender, EventArgs e)
{
textBox4.Text = "";
int[] count = new int[10]{0,0,0,0,0,0,0,0,0,0};
ArrayList arr = new ArrayList();
Random rd = new Random();
int allcount = Convert.ToInt32(txtAllCount.Text.Trim());//总数
int min = Convert.ToInt32(textBox3.Text.Trim());
int max= Convert.ToInt32(textBox5.Text.Trim());
int start = Convert.ToInt32(textBox1.Text.Trim());
int end = Convert.ToInt32(textBox2.Text.Trim());
int percentnum = (int)(Convert.ToDouble(comboBox1.Text.Trim()) / 100.0 * allcount);
int lastnum = allcount - percentnum;
CustomRandom mycust = new CustomRandom();
Stopwatch sw1 = new Stopwatch();
sw1.Start();
arr = mycust.customRandomCalc(allcount, min, max, start, end, Convert.ToDouble(comboBox1.Text.Trim()) / 100.0);
//int index = 0;
//int value = 0;
//while (true)
//{
// value = rd.Next(start, end + 1);
// arr.Add(value);
// if (++index >= percentnum)
// {
// break;
// }
//}
//index = 0;
//while (true)
//{
// value = rd.Next(min, max + 1);
// if (value >= start && value <= end)
// {
// continue;
// }
// else
// {
// arr.Add(value);
// if (++index >= lastnum)
// {
// break;
// }
// }
//}
sw1.Stop();
TimeSpan ts1 = sw1.Elapsed;
textBox6.Text = ts1.TotalMilliseconds.ToString() + "ms";
ArrayList arr2 = new ArrayList();
Random rd2 = new Random();
int cccc = 0;
Stopwatch sw2 = new Stopwatch();
sw2.Start();
int value2 = 0;
while (true)
{
value2 = rd2.Next(min, max + 1);
arr2.Add(value2);
if (++cccc > allcount)
{
break;
}
}
sw2.Stop();
TimeSpan ts2 = sw2.Elapsed;
textBox7.Text = ts2.TotalMilliseconds.ToString() + "ms";
arr.Sort();
int counta = 0;
int countb = 0;
string outStr=null;
foreach (int i in arr)
{
outStr += i + ",";
if (i >= start && i <= end)
{
countb++;
}
counta++;
}
listBox1.Items.Clear();
textBox4.Text = outStr.Trim(',');
listBox1.Items.Add("总个数:"+counta.ToString());
listBox1.Items.Add("自定义:" + countb.ToString());
int pec = (int)((countb*1.0) / (counta*1.0) * 100+0.4);
listBox1.Items.Add("百分比:" + pec.ToString()+"%");
}
class CustomRandom
{
public int sampleCount { get; set; }//样本总数
public int sampleMin { get; set; }//样本起始值
public int sampleMax { get; set; }//样本结束值
public int customMin { get; set; }//自定义样本区间起始值
public int customMax { get; set; }//自定义样本区间结束值
public double customPercent { get; set; }//自定义样本占比
public ArrayList customRandomCalc(int sampleCount, int sampleMin, int sampleMax, int customMin, int customMax, double customPercent)
{
ArrayList valueList = new ArrayList ();
Random rd = new Random();
int index = 0;
int value = 0;
int percentnum = (int)(customPercent * sampleCount);
while (true)
{
value = rd.Next(customMin, customMax + 1);
valueList.Add(value);
if (++index >= percentnum)
{
break;
}
}
index = 0;
while (true)
{
value = rd.Next(sampleMin, sampleMax + 1);
if (value >= customMin && value <= customMax)
{
continue;
}
else
{
valueList.Add(value);
if (++index >= (sampleCount - percentnum))
{
break;
}
}
}
return valueList;
}
}
//目前这个简单功能已经能够满足项目使用,如果更高效的方法欢迎推荐!