随机指定范围内N个不重复的数

此为工具类,支持抽奖业务需求,具体实现见下方代码:

package com.org.test;

import java.util.ArrayList;
import java.util.List;

public class RandomUtil {

    /**
     * 随机抽出中奖用户下标 
     * 当max < count时,输出max+1个,  如 0,2,5  输出3个结果
     * 当max = count时,输出 count个, 如 0,2,2  输出2个结果
     * 当max > count 时,输出count个,如 0,5,3  输出3个结果
     * @param min
     * @param max
     * @param count
     * @return
     * @author Shindo   
     * @date 2017年1月7日 下午5:00:14
     */
    public static int[] getRandomArray(int min, int max, int count) {
        List<Integer> randomCommon = randomCommon(min, max, count);
        int size = randomCommon.size();
        int[] result = new int[size];
        if (size > 0) {
            for (int j = 0; j < randomCommon.size(); j++) {
                Integer integer = randomCommon.get(j);
                result[j] = integer;
            }
            System.out.println("随机下标:");
            for (int k = 0; k < result.length; k++) {
                System.out.println(result[k]);
            }
        }
        return result;
    }

    /**
     * 随机指定范围内N个不重复的数 
     * @param min 指定范围最小值 
     * @param max 指定范围最大值 
     * @param n   随机数个数 
     * @return
     */
    public static List<Integer> randomCommon(int min, int max, int n) {
        List<Integer> integers = new ArrayList<Integer>();
        if (min < 0) {
            min = 0;
        }
        if ((max - min) + 1 < n) {
            n = (max - min) + 1;
        }
        if (max < min) {
            max = min;
        }
        if (max < 0 || n < 0) {
            return integers;
        }
        for (int i = 1; i <= n; i++) {
            int randomNumber = (int) Math.round(Math.random() * (max - min) + min);
            if (integers.contains(randomNumber)) {
                i--;
                continue;
            } else {
                integers.add(randomNumber);
            }
        }
        return integers;
    }

    // 测试随机数获取
    public static void main(String[] args) {

        // 当max < count时,输出max+1个,当max = count时,输出 count个, 当max > count 时,输出count个
        List<Integer> randomCommon = randomCommon(0, 8, 3);

        for (int j = 0; j < randomCommon.size(); j++) {
            Integer integer = randomCommon.get(j);
            System.out.println(integer);
        }
        System.out.println("\n");
        int size = randomCommon.size();
        int[] result = new int[size];
        if (size > 0) {
            for (int j = 0; j < randomCommon.size(); j++) {
                Integer integer = randomCommon.get(j);
                result[j] = integer;
            }
            System.out.println("抽奖下标打印输出");
            for (int k = 0; k < result.length; k++) {
                System.out.println(result[k]);
            }
        }

    }

}

  

 

posted @ 2017-01-24 11:17  shindoyang  阅读(1487)  评论(0编辑  收藏  举报