List<Integer> seed = new LinkedList<Integer>(); for (int i = 1; i <= 15; i++) { seed.add(i); } Random rand = new Random(); while (!seed.isEmpty()) { System.out.println(seed.remove(rand.nextInt(seed.size()))); }
public class Main { public static void main(String[] args) { Item item = new Item(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); while (item.hash()) { System.out.println(item.get()); } } }class Item<T> { Object[] objs; int offer = 0; public Item(T[] o) { objs = new Object[o.length]; System.arraycopy(o, 0, objs, 0, objs.length); init(); } private void init() { //打乱数组 Random r = new Random(); for (int i = objs.length - 1; i > 0; i--) { int pos = r.nextInt(i + 1); Object buf = objs[i]; objs[i] = objs[pos]; objs[pos] = buf; } } public boolean hash() { return offer < objs.length; } public T get() { if (offer < objs.length) { return (T) objs[offer++]; } return null; } }
每次remove后size难道不减一?
import java.util.*;
public class RandomTest{ public static void generateRandom(int n){ if(n<=0) { System.out.println("不符合要求"); } Set<Integer> mySet = new HashSet<Integer>(); Random random = new Random(); do{ int temp = random.nextInt(n)+1; if(!mySet.contains(temp)){ mySet.add(temp); System.out.println(temp); } }while(mySet.size()<n); } public static void main(String[] args){ generateRandom(15); } }
for (int i = 1; i <= 15; i++) {
seed.add(i);
}
Random rand = new Random();
while (!seed.isEmpty()) {
System.out.println(seed.remove(rand.nextInt(seed.size())));
}
public class Main { public static void main(String[] args) {
Item item = new Item(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
while (item.hash()) {
System.out.println(item.get());
}
}
}class Item<T> { Object[] objs;
int offer = 0; public Item(T[] o) {
objs = new Object[o.length];
System.arraycopy(o, 0, objs, 0, objs.length);
init();
} private void init() {
//打乱数组
Random r = new Random();
for (int i = objs.length - 1; i > 0; i--) {
int pos = r.nextInt(i + 1);
Object buf = objs[i];
objs[i] = objs[pos];
objs[pos] = buf;
}
} public boolean hash() {
return offer < objs.length;
} public T get() {
if (offer < objs.length) {
return (T) objs[offer++];
}
return null;
}
}
每次remove后size难道不减一?
public class RandomTest{
public static void generateRandom(int n){
if(n<=0) {
System.out.println("不符合要求");
}
Set<Integer> mySet = new HashSet<Integer>();
Random random = new Random();
do{
int temp = random.nextInt(n)+1;
if(!mySet.contains(temp)){
mySet.add(temp);
System.out.println(temp);
}
}while(mySet.size()<n);
}
public static void main(String[] args){
generateRandom(15);
}
}