加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java随机生成前N个不重复的整数

发布时间:2020-12-14 23:17:36 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

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("rn");  
                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;    
    }  
}  

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读