LALA  
日历
<2015年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

留言簿(1)

随笔分类(31)

文章分类(4)

收藏夹(21)

搜索

  •  

积分与排名

  • 积分 - 28914
  • 排名 - 1402

最新随笔

最新评论

阅读排行榜

 
比较好的生成随机序列的算法:
 
 1 import java.util.Random;
 2 
 3 public class Utility {
 4     /**
 5      * 用0~n生成m个数的随机序列
 6      * 
 7      * @param limit
 8      *            - n-1
 9      * @param need
10      *            - m
11      * @return 生成的随机序列
12      */
13     public static int[] random_serial(int limit, int need) {
14         int[] temp = new int[limit];
15         int[] result = new int[need];
16         for (int i = 0; i < limit; i++)
17             temp[i] = i;
18         int w;
19         Random rand = new Random();
20         for (int i = 0; i < need; i++) {
21             w = rand.nextInt(limit - i) + i;
22             int t = temp[i];
23             temp[i] = temp[w];
24             temp[w] = t;
25             result[i] = temp[i];
26         }
27         return result;
28     }
29 
30     /**
31      * 对0~n进行随机乱序排列,比如用于歌曲随机播放。
32      *  1、按顺序用0到n填满整个数组;
33      *  2、随机产生从0到n-2个数组下标,把这个下标的元素值跟n-1下标的元素值交换,
34      *     一直进行到下标为1的元素。
35      * 因此它只需要遍历一次就能产生全部的随机数。
36      * 
37      * @param limit
38      *            - n-1
39      * @return 生成的随机序列
40      */
41     public static int[] random_serial(int limit) {
42         int[] result = new int[limit];
43         for (int i = 0; i < limit; i++)
44             result[i] = i;
45         int w;
46         Random rand = new Random();
47         for (int i = limit - 1; i > 0; i--) {
48             w = rand.nextInt(i);
49             int t = result[i];
50             result[i] = result[w];
51             result[w] = t;
52         }
53         return result;
54     }
55 }
56 
posted on 2008-12-23 17:32 Dest 阅读(1805) 评论(1)  编辑  收藏 所属分类: Java算法
 
Copyright © Dest Powered by: 博客园 模板提供:沪江博客