要产生M个0-N的不同的随机数,方案?
1:将产生的随机数放入到集合中,产生一个随机数判断是否在集合中,不在的话放入,知道集合为M为止
2:
Algorithm F2
init set S to empty
size = 0
for j = n - m + 1 to n
t = random(1,j)
if t is not in S then
insert t to S
else
insert j to S
算法实现如下:
package test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
public class Odd {
public static void main(String[] args) {
//System.out.println((-5)%2);
random(50,100);
randomFloyd(50,100);
}
//Floyd的算法
static void randomFloyd(int m,int n)
{
int index=0;
Random r=new Random();
HashSet<integer> hs=new HashSet<integer>();
for (int i = n-m+1; i <=n; i++) {
int k=r.nextInt(i);
if(!hs.contains(k))
hs.add(k);
else
hs.add(i);
index++;
}
System.out.println("运行"+index+"次");
System.out.println(Arrays.toString(hs.toArray()));
System.out.println(hs.size());
}
//算法1
static void random(int m,int n){
int index=0;
Random r=new Random();
HashSet<integer> hs=new HashSet<integer>();
while (hs.size()!=m) {
int k=r.nextInt(n);
if(!hs.contains(k))
hs.add(k);
index++;
}
System.out.println("运行"+index+"次");
System.out.println(Arrays.toString(hs.toArray()));
}
}
运行结果:
运行68次
[0, 5, 8, 10, 12, 14, 15, 19, 18, 20, 23, 25, 28, 31, 30, 33, 39, 36, 37, 42, 46, 47, 44, 51, 54, 52, 57, 63, 62, 68, 69, 70, 71, 64, 65, 76, 72, 74, 75, 84, 87, 86, 81, 82, 92, 94, 88, 91, 90, 98]
运行50次
[1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 15, 17, 16, 18, 21, 25, 29, 28, 31, 30, 32, 33, 36, 42, 50, 49, 48, 53, 59, 62, 61, 60, 69, 70, 64, 67, 78, 79, 74, 86, 80, 83, 82, 93, 92, 94, 91, 90, 97]
1:将产生的随机数放入到集合中,产生一个随机数判断是否在集合中,不在的话放入,知道集合为M为止
2:
Algorithm F2
init set S to empty
size = 0
for j = n - m + 1 to n
t = random(1,j)
if t is not in S then
insert t to S
else
insert j to S
算法实现如下:
package test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
public class Odd {
public static void main(String[] args) {
//System.out.println((-5)%2);
random(50,100);
randomFloyd(50,100);
}
//Floyd的算法
static void randomFloyd(int m,int n)
{
int index=0;
Random r=new Random();
HashSet<integer> hs=new HashSet<integer>();
for (int i = n-m+1; i <=n; i++) {
int k=r.nextInt(i);
if(!hs.contains(k))
hs.add(k);
else
hs.add(i);
index++;
}
System.out.println("运行"+index+"次");
System.out.println(Arrays.toString(hs.toArray()));
System.out.println(hs.size());
}
//算法1
static void random(int m,int n){
int index=0;
Random r=new Random();
HashSet<integer> hs=new HashSet<integer>();
while (hs.size()!=m) {
int k=r.nextInt(n);
if(!hs.contains(k))
hs.add(k);
index++;
}
System.out.println("运行"+index+"次");
System.out.println(Arrays.toString(hs.toArray()));
}
}
运行结果:
运行68次
[0, 5, 8, 10, 12, 14, 15, 19, 18, 20, 23, 25, 28, 31, 30, 33, 39, 36, 37, 42, 46, 47, 44, 51, 54, 52, 57, 63, 62, 68, 69, 70, 71, 64, 65, 76, 72, 74, 75, 84, 87, 86, 81, 82, 92, 94, 88, 91, 90, 98]
运行50次
[1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 15, 17, 16, 18, 21, 25, 29, 28, 31, 30, 32, 33, 36, 42, 50, 49, 48, 53, 59, 62, 61, 60, 69, 70, 64, 67, 78, 79, 74, 86, 80, 83, 82, 93, 92, 94, 91, 90, 97]