日期:2014-05-20  浏览次数:20707 次

JAVA 随机数 Random,求高手
* 随机产生7个随机数,前六个数字的范围是从1至33,第7个数的范围是从1至22。

* 就只有一个要求
* 前六个的数字是1至33之间不重复的数。


import java.util.Random;

public class SSQiu {

/**
* @param args
* 随机产生7个随机数,前六个数字的范围是从1至33,第7个数的范围是从1至22。

* 就只有一个要求
* 前六个的数字是1至33之间不重复的数。

* 这个程序感觉写的很复杂,有没有简单一点的写法,求高手

*/

public static final int SCOPE_1_6 = 33; //The first sixth number's scope is from 1 to 33,including 1 and 33 ,(1 <= X <= 33) 

public static final int SCOPE_7 = 22; // The first seventh number's scope is from 1 to 22,including 1 and 22 ,(1 <= X <= 22)

public static final int NUM = 7; // The ShuangSeQiu including 7 numbers


private static boolean alreadyExisted(int[] result, int key ,boolean firstTime ,int index) {

boolean flag = false;

if(!firstTime){
for (int i = 0; i < index ; i++) {

if (result[i] == key) {

flag = true;

break;

}
}
}


return flag;

}

public static void main(String[] args) {
// TODO Auto-generated method stub
Random rd = new Random();

int[] result = new int[NUM];

for (int i = 0; i < result.length; i++) {

result[i] = -1;
}
boolean[] flag = new boolean[SCOPE_1_6 + 1];

for (int i = 1; i <= SCOPE_1_6; i++) {

flag[i] = true;

}


int key = 1;

int index = 0;

int count = 0;

boolean firstTime = true;

while (true) {

key = Math.abs(rd.nextInt() % (SCOPE_1_6 + 1));
while (key < 1) {
key = Math.abs(rd.nextInt() % (SCOPE_1_6 + 1));
}

result[index] = key;

if (!alreadyExisted(result, key,firstTime,index)) {

index++;
count++;

}
if(index >= NUM -1 ){
break;
}

firstTime = false;

}



key = Math.abs(rd.nextInt() % (SCOPE_7 + 1));
while (key < 1) {
key = Math.abs(rd.nextInt() % (SCOPE_7 + 1));
}
result[NUM - 1] = key;

int sum = 0;

System.out.print("The " + NUM + " random's number is :");

for (int i = 0; i < result.length; i++) {
sum = sum + result[i];

System.out.print("["+result[i] + "] ");

}

System.out.println( );
System.out.println("sum[" + result.length + "] = " + sum );
}

}




------解决方案--------------------
你参考下,用java提供的随机数生成
Java code

import java.util.List;
import java.util.ArrayList;


public class RandomNumberFactory {
    public static final int NUM = 7;

    public List<Integer> getRandowNumbers(){
        List<Integer> list=new ArrayList<Integer>();

        for(int j=0;list.size()!=6;j++){
            int i=1+(int)(Math.random()*33);

            if(!list.contains(i)&&list.size()!=6){
                list.add(i);
            }
        }
        for(int i=0;list.size()!=7;i++){
            int j=1+(int)(Math.random()*22);

            if(!list.contains(j)&&list.size()!=7){
                list.add(j);
            }
        }

//        i=1+(int)(Math.random()*22);

        return list;
    }

    public static void main(String[] args) {
        RandomNumberFactory factory=new RandomNumberFactory();
        for(int i:factory.getRandowNumbers()){
            System.out.println(i);
        }
    }
}

------解决方案--------------------
借助Collections的shuffle()写了一个,供参考。
Java code