Java隨機生成前N個不重復的整數

puye 9年前發布 | 5K 次閱讀 Java

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**

  • 測試隨機生成前N個不重復的整數
  • @author Administrator
  • */
    public class TestRandom {
    public static void main(String[] args) {

     randomNumber2File("e:/random.txt");  
    

    }

    /**

    • 根據提供的路徑生成相應的隨機數
    • @param path */
      public static void randomNumber2File(String path){
      File file = new File(path);
      OutputStream os = null;
      try {

       os = new BufferedOutputStream(new FileOutputStream(file));  
       byte[] buf = new byte[20];  
       for(int j = 0; j < 100; j++){  
           int[] arr = ranInt(9);  
           StringBuffer sb = new StringBuffer();  
           for(int i = 0; i < arr.length; i++){  
               sb.append(arr[i]);  
           }  
           sb.append("\r\n");  
           buf = sb.toString().getBytes();  
           os.write(buf);  
       }  
      

      } catch (FileNotFoundException e) {

       e.printStackTrace();  
      

      } catch (IOException e) {

       e.printStackTrace();  
      

      }finally{

       if(null != os){  
           try {  
               os.close();  
           } catch (IOException e) {  
               // TODO Auto-generated catch block  
               e.printStackTrace();  
           }  
       }  
      

      }
      }

      /**

    • 利用隨機生成數組的索引實現隨機,并通過交換實現不重復
    • @param n
    • @return */
      public static int[] ranInt(int n) {
      int[] arr = new int[n];
      int i,randomIndex,temp;
      for(i = 0; i < n; i++){

       arr[i] = i+1;  
      

      }
      for(i = 1; i < n; i++){

       randomIndex = ranIndex(0, i);  
       //交換當前元素和生成的隨機元素  
       temp = arr[i];  
       arr[i] = arr[randomIndex];  
       arr[randomIndex] = temp;  
      

      }
      return arr;
      }

      public static int ranIndex(int start, int end){
      Random r = new Random();
      int result;
      result = r.nextInt(end);
      return result;
      }
      } </pre>

 本文由用戶 puye 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!