随机生成不同的随机数
2016-04-07 09:54
211 查看
1.函数
//生成随机1-16的三个不同的随机数
public int[] getRandomNum(int num, int minValue, int maxValue)
{
Random ra = new Random(unchecked((int)DateTime.Now.Ticks));
int[] arrNum = new int[num];
int tmp = 0;
for (int i = 0; i <= num - 1; i++)
{
tmp = ra.Next(minValue, maxValue); //随机取数
arrNum[i] = getNum(arrNum, tmp, minValue, maxValue, ra); //取出值赋到数组中
}
return arrNum;
}
public int getNum(int[] arrNum, int tmp, int minValue, int maxValue, Random ra)
{
int n = 0;
//while (n <= arrNum.Length - 1)
for (n = 0; n <= arrNum.Length - 1; n++)
{
if (arrNum
== tmp) //利用循环判断是否有重复
{
tmp = ra.Next(minValue, maxValue); //重新随机获取。
getNum(arrNum, tmp, minValue, maxValue, ra);//递归:如果取出来的数字和已取得的数字有重复就重新随机获取。
}
}
return tmp;
}
2.调用
int[] arr = getRandomNum(3, 1, 16); //从1至16中取出3个互不相同的随机数
//生成随机1-16的三个不同的随机数
public int[] getRandomNum(int num, int minValue, int maxValue)
{
Random ra = new Random(unchecked((int)DateTime.Now.Ticks));
int[] arrNum = new int[num];
int tmp = 0;
for (int i = 0; i <= num - 1; i++)
{
tmp = ra.Next(minValue, maxValue); //随机取数
arrNum[i] = getNum(arrNum, tmp, minValue, maxValue, ra); //取出值赋到数组中
}
return arrNum;
}
public int getNum(int[] arrNum, int tmp, int minValue, int maxValue, Random ra)
{
int n = 0;
//while (n <= arrNum.Length - 1)
for (n = 0; n <= arrNum.Length - 1; n++)
{
if (arrNum
== tmp) //利用循环判断是否有重复
{
tmp = ra.Next(minValue, maxValue); //重新随机获取。
getNum(arrNum, tmp, minValue, maxValue, ra);//递归:如果取出来的数字和已取得的数字有重复就重新随机获取。
}
}
return tmp;
}
2.调用
int[] arr = getRandomNum(3, 1, 16); //从1至16中取出3个互不相同的随机数
相关文章推荐
- iOS开发学习之 - 正则表达式在IOS中的应用
- linux下ls命令详解
- 每天laravel-20160702|CacheTableCommand
- 【笔试/面试】 —— 最长递增子序列
- ios学习之plist文件的读写以及存储位置的探究
- 分类模型到底如何选择
- 从头认识多线程-1.1 多线程的创建
- window.open详解
- WEB测试方法
- Linux查看物理CPU个数、核数、逻辑CPU个数
- jQuery 属性操作 - removeAttr() 方法
- poj3186 dp
- php中高级基础知识点
- Spark RDD揭秘
- 设计模式之命令模式
- 再玩 DevStack(Mitaka版)- 基于 trystack.cn 源
- DefaultAnnotationHandlerMapping 和 AnnotationMethodHandlerAdapter 的使用已经过时!
- 神经网络基本概念
- Android Studio debug使用release的签名
- win7启动本地MongoDB的四种方式