如何产生0至n-1之间k个不同的随机顺序的随机整数
如题,不知大家有什么好的想法,比如n = 10000000 ,求1000000个小于n的随机数,这些数不重复,顺序是乱的。
谢谢。
[最优解释]
public static void main(String[] args) {
int n = 10000000, k = 1000000;
boolean[] appear = new boolean[n];
Random r = new Random();
int[] nums = new int[k];
for (int i = 0; i < k; i++) {
int j = -1;
while (appear[j = r.nextInt(n)]);
nums[i] = j;
//appear[j] = true;System.out.println(nums[i]);
}
}
package com;
import java.util.ArrayList;
import java.util.List;
public class B {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List list=new ArrayList<Integer>();
for(int i=1;i<=10000000;i++){
list.add(i);
}
long start=System.currentTimeMillis();
java.util.Collections.shuffle(list);
System.out.println(System.currentTimeMillis()-start);
}
}
public static void main(String[] args) {
int n = 10000000, k = 1000000;
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = i;
Random r = new Random();
int[] nums = new int[k];
for (int i = 0; i < k; i++) {
int j = r.nextInt(n - i) + i;
nums[i] = arr[j];
arr[j] = arr[i];
}
}
package com;
import java.util.ArrayList;
import java.util.List;
public class Test4 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List list = new ArrayList<Integer>();
for (int i = 1; i <= 54; i++) {
list.add(i);
}
while (list.size() > 0) {
int size = list.size();
int r = (int) (java.lang.Math.random() * size);
System.out.println(list.get(r));
list.remove(r);
}
}
}
}while(r.size()<k);
//System.out.println(r.size());
for(int j=0;j<r.size();j++)
{
Test tj=(Test)r.elementAt(j);
System.out.println(tj.getnum());
}
}
}
[其他解释]
经典的洗牌算法。
[其他解释]
public static void main(String[] args) {
long start = System.currentTimeMillis();
int n = 10000000;
int k = 9000000;
Set<Integer> set = new HashSet<Integer>();
Random rand = new Random();
while (set.size() < k) {
set.add(rand.nextInt(n));
}
System.out.println("set's size :" + set.size()) ;
System.out.println(System.currentTimeMillis() - start);
}
package com;
import java.util.ArrayList;
import java.util.List;
public class Test2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List list = new ArrayList<Integer>();
for (int i = 1; i <= 10000000; i++) {
list.add(i);
}
while (list.size() > 9000000) {
int size = list.size();
int r = (int) (java.lang.Math.random() * size);
System.out.println(list.get(r));
list.remove(r);
}
}
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
int n = 10000000;
int k = 1000000;
boolean[] appear = new boolean[n];
Random rand = new Random();
int [] jj = new int [k];
for (int i = 0 ; i < k ; i ++) {
int j = -1 ;
while (appear[j = rand.nextInt(n)]);
jj[i] = j;
appear[j] = true;
}
System.out.println("jj'length:" + jj.length);
System.out.println(System.currentTimeMillis() - start);
}