提供思路
用java的随机方法生成一个数字,然后mod 12,如果和前面的数值有相同的,那么抛弃这个数值,否则保存,直到数组中有12个数为止。还有一种方法可以这样实现:定义一个数组,长度为输入的数组的长,在得到输入的整数,即其长度时进行初始化,a[0]=1,a[1]=2,a[2]=3,......,a[11]=12。然后生成的数组为b[12],用随机函数产生1到12的整数,作为a数组的下标,然后顺序赋值给b数组,赋值过的a就讲其值置为0,每次在赋值b之前检查这个a是不是0,不是则赋值,是则再得到另外一个a。这比上一个算法应该好点吧。

解决方案 »

  1.   

    还有一个就是每次mod的时候都减少一个数值
    比如第一次mod 12,第二此mod 11………………这样的话可以每次mod都得到一个数值
    但是每次都要对原先的数组进行重新排列,这样就保证每次都可以得到一个随机数,不会浪费太多的时间了。这个方法是上述第二个算法的改进。讲的乱七八糟,呵呵
      

  2.   

    输入n,返回包含1~n之间的n个整数的数组 public int[] myRand(int n){
    int[] result = new int[n];

    ArrayList al = new ArrayList();
    for ( int i = 1; i <= n; i++ ){
    al.add( new Integer(i));
    }

    // 
    for ( int i = 0; i < n; i++){
    Random r = new Random();
    int index = r.nextInt(n-i);
    Object o = al.get(index);
    result[i] = ((Integer)o).intValue();

    // remove 
    al.remove(index);
    }

    return result;
    }
      

  3.   

    完整代码如下:import java.util.ArrayList;
    import java.util.Random;
    public class Test { public static void main(String[] args) {
    Test test = new Test();
    for ( int n = 2 ;n < 20; n++){
    int[] r = test.myRand(n);
    System.out.println( n + ": " + test.arrayToString(r,", "));
    }

    }

    public int[] myRand(int n){
    int[] result = new int[n];

    ArrayList al = new ArrayList();
    for ( int i = 1; i <= n; i++ ){
    al.add( new Integer(i));
    }

    // 
    for ( int i = 0; i < n; i++){
    Random r = new Random();
    int index = r.nextInt(n-i);
    Object o = al.get(index);
    result[i] = ((Integer)o).intValue();

    // remove 
    al.remove(index);
    }

    return result;
    }

    // print int[]
    private String arrayToString( int[] intArray, String strSeparator){
    StringBuffer sb = new StringBuffer();
    if( strSeparator == null ) strSeparator = ",";
    int i = 0;
    for( i = 0; i < intArray.length-1; i++){
    sb.append( intArray[i] + strSeparator );
    }
    sb.append( intArray[i]);

    // return
    return sb.toString();
    }
    }