您的位置:首页 > 其它

产生一个int数组,长度为100,并向其中随机插入1-100,并且不能重复。按照数组下标输出结果。

2012-07-02 16:01 609 查看
功能如题,

思路:

生成一个数组,

数组的特点是:每个元素是1-100之间的随机数,插入数组的时候判断是否已经存在,

若存在,数组的索引回复到之前,-1,继续生成随机数,插入数据,

若是不存在,直接插入数组。

注意一点:用计算机时间作为随机种子,已尽可能保证生成随机的伪随机数,详情参考(http://www.cnblogs.com/falla/archive/2010/01/29/1659399.html)

Random ra = new Random(unchecked((int)DateTime.Now.Ticks));

View Code

protected void Page_Load(object sender, EventArgs e)
{
int[] arr = numList(10, 1, 15);
for (int i = 0; i < arr.Length; i++)
{
Response.Write("第" + i + "个:" + arr[i].ToString() + "<br/>");
}
}
public int[] numList(int count, int minValue, int maxValue)
{
Random ra = new Random(unchecked((int)DateTime.Now.Ticks));
int[] numlist = new int[count];
for (int i = 0; i < count; i++)
{
int t = ra.Next(minValue, maxValue);
if (!checkNumList(numlist, t))
{
numlist[i] = t;
}
else
{
i--;
}
}
return numlist;
}
//已存在返回true
public bool checkNumList(int[] numlist, int c)
{
foreach (int t in numlist)
{
if (t!=null)
{
if (t == c)
{
return true;
}
}
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐