当前位置: 代码迷 >> J2SE >> random随机数有关问题
  详细解决方案

random随机数有关问题

热度:46   发布时间:2016-04-24 13:51:34.0
random随机数问题
random   ran=new   random;
a.setseed(1);
for(int   i=0;i <19;i++)
{
        ran.nextInt(100);
}
大致是这个意思   我想随机显示20个(1-100之间的数字)
我设置了种子   1   上限100
但是我不想数字重复   该怎么写啊  
求高手

------解决方案--------------------
google 洗牌算法
------解决方案--------------------
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

public class Test2 {

  public static void main(String[] args) {
    Random ran = new Random();
    ran.setSeed(1);
    Set <Integer> set = new TreeSet <Integer> ();
    while (set.size() < 20) {
      set.add(ran.nextInt(100));
    }

    // 输出
    int i = 1;
    for (int num : set) {
      System.out.printf( "%2d%s ", num, (i++) % 5 == 0 ? "\n " : " ");
    }
  }
}
------解决方案--------------------
import java.util.Random;
public class Test {
public static void main(String[] args) {
Random ran=new Random();
ran.setSeed(1);
String rnd = " ";
StringBuffer rs = new StringBuffer( " ");
for(int i=0;i <20;i++) {
rnd = String.valueOf(ran.nextInt(100));
if (rs.indexOf(rnd) < 0) {
rs.append(rnd + " ");
}
}
System.out.print(rs.toString());
}
}
------解决方案--------------------
import java.util.*;

public class Test{
public static void main(String[] args){
boolean[] cards = new boolean[20];
for(int index=0; index <20; index++){
cards[index]=false;
}
Random r=new Random();
int x;
for (int index=0; index <20;index++){
do{
x=r.nextInt(100);
}while(cards[x/5]!=false);
cards[x/5]=true;
System.out.print(x+ " ");
}
}
}
------解决方案--------------------
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;

public class random {

public static void main(String[] args) {
Random ran = new Random();
Set set = new HashSet();
while(set.size() <20)
{
set.add(new Integer(ran.nextInt(1000)));
}
Iterator bb = set.iterator();
while(bb.hasNext())
{
System.out.println(bb.next().toString());
}

}
  相关解决方案