生成1千万不重复的数字


package com.myway.study;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

/**
 * 
 * 生成1千万不重复的数字
 * User: zhangyong
 * Date: 14-5-2
 * Time: 下午11:02
 * To change this template use File | Settings | File Templates.
 */
public class TenMillionNotCurrentNumber {

    public static void main(String[] args) {
        int max = 10000000;
        Random random = new Random();
        int[] arr = new int[max];
        System.out.println(arr.length);
        String storePath = "D:\\1.txt";
        //设置初始值
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i + 1;
        }
        //调用随机来调换位置
        for (int n = 0; n < max; n++) {
            int ii = (int) random.nextInt(max);
            if (ii == max) {
                ii = ii - 1;
            }
            int jj = (int) random.nextInt(max);
            if (jj == max) {
                jj = jj - 1;
            }
            //调换位置
            swap(arr, ii, jj);
        }
        for (int i = 0; i < arr.length; i++) {
            try {
                String data = (i == arr.length - 1) ? String.valueOf(arr[i]) : (String.valueOf(arr[i]) + ',');
                FileUtils.writeStringToFile(new File(storePath), data, true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void swap(int[] arr, int ii, int jj) {
        int temp = arr[ii];
        arr[ii] = arr[jj];
        arr[jj] = temp;
    }


}

你可能感兴趣的:(java)