博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

一段关于获取随机数的代码

Posted on 2018-09-19 19:05  激流勇进、  阅读(264)  评论(0编辑  收藏  举报

我觉得比较精妙吧。   注意,第一个参数不要比第二个参数大。

 

 1 public static int[] randon(int num, int length)
 2     {
 3         boolean[] cards = new boolean[length];
 4         
 5         for (int r = 0; r < length; ++r)
 6         {
 7             cards[r] = false;
 8         }
 9         
10         Random arg6 = new Random();
11         int[] result = new int[num];
12         
13         for (int index = 0; index < num; ++index)
14         {
15             int x;
16             do
17             {
18                 x = arg6.nextInt(length);
19             } while (cards[x]);
20             
21             cards[x] = true;
22             result[index] = x;
23         }
24         
25         return result;
26     }

 

再来一段

 

 1 public static String[] randomRank(String[] bookIDs, int num)
 2     {
 3         if (null != bookIDs && 0 != bookIDs.length)
 4         {
 5             if (num >= bookIDs.length)
 6             {
 7                 num = bookIDs.length;
 8             }
 9             
10             ArrayList list = new ArrayList(bookIDs.length);
11             
12             for (int ran = 0; ran < bookIDs.length; ++ran)
13             {
14                 list.add(bookIDs[ran]);
15             }
16             
17             int[] arg6 = randon(num, bookIDs.length);
18             ArrayList reList = new ArrayList(bookIDs.length);
19             
20             int ids;
21             for (ids = 0; ids < arg6.length; ++ids)
22             {
23                 String o = (String)list.get(arg6[ids]);
24                 reList.add(o);
25             }
26             
27             for (ids = 0; ids < reList.size(); ++ids)
28             {
29                 list.remove(reList.get(ids));
30             }
31             
32             reList.addAll(list);
33             String[] arg7 = new String[reList.size()];
34             return (String[])((String[])reList.toArray(arg7));
35         }
36         else
37         {
38             return null;
39         }
40     }