Generate not repeat random numbers


for(int i=;i<100;i++){

ArrayList<Integer> tmp_l = new ArrayList<Integer>();

int pos = 100;
int serial = (int)Math.round(Math.random()*(pos-1));
int loopcontrol = 0;

while(tmp_l.contains(serial)){
    if(loopcontrol>100) break;
    serial = (int)Math.round(Math.random()*(pos-1));
    loopcontrol ++;
}
   
tmp_l.add(serial);

System.out.println(“The random number for “+i+” is:”+serial);

}

只給出代碼片段,

先有機出一個數,保存在ArrayList,再有機第二個數,看看是否存在於ArrayList中,如果存在,再重新有機第二個數.如此類推..直到完成100個有機數為此!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.