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

          導航

          留言簿(1)

          隨筆分類(31)

          文章分類(4)

          收藏夾(21)

          搜索

          •  

          積分與排名

          • 積分 - 30078
          • 排名 - 1390

          最新隨筆

          最新評論

          閱讀排行榜

           
          比較好的生成隨機序列的算法:
           
           1 import java.util.Random;
           2 
           3 public class Utility {
           4     /**
           5      * 用0~n生成m個數(shù)的隨機序列
           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填滿整個數(shù)組;
          33      *  2、隨機產(chǎn)生從0到n-2個數(shù)組下標,把這個下標的元素值跟n-1下標的元素值交換,
          34      *     一直進行到下標為1的元素。
          35      * 因此它只需要遍歷一次就能產(chǎn)生全部的隨機數(shù)。
          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 閱讀(1837) 評論(1)  編輯  收藏 所屬分類: Java算法
           
          Copyright © Dest Powered by: 博客園 模板提供:滬江博客
          主站蜘蛛池模板: 上饶市| 台南市| 贺兰县| 伊金霍洛旗| 鱼台县| 崇阳县| 甘德县| 巫溪县| 岢岚县| 宁都县| 个旧市| 左权县| 虎林市| 万宁市| 巴马| 平泉县| 离岛区| 东阳市| 二连浩特市| 靖江市| 平和县| 太湖县| 区。| 阆中市| 青龙| 广南县| 汤原县| 册亨县| 清远市| 栾川县| 布尔津县| 吴川市| 泊头市| 山东省| 普洱| 浮山县| 黎川县| 禹州市| 梧州市| 东安县| 惠水县|