java经典算法_035

package wzs.arithmetics;

// 随机数
public class Test
{

    public static void main(String[] args)
    {
        int[] test = getRandomIntWithoutReduplicate(0, 10, 5);
        // Arrays.sort(test);
        for (int i : test)
        {
            System.out.print(i + " ");
        }
    }

    /**
     * 返回一个不重复的随机数数组 [min, max)
     * @param 最小随机数
     * @param 最大随机数
     * @param 数组长度
     * @return 一个没有重复值的数组
     */
    public static int[] getRandomIntWithoutReduplicate(int min, int max, int size)
    {
        int[] result = new int[size]; // 数组容器
        int arraySize = max - min; // 数组范围
        int[] intArray = new int[arraySize];
        // 初始化数组
        for (int i = 0; i < intArray.length; i++)
        {
            intArray[i] = i + min;
        }
        // 得到不重复的数组
        for (int i = 0; i < size; i++)
        {
            int c = getRandomInt(min, max - i);
            int index = c - min;
            swap(intArray, index, arraySize - 1 - i);
            result[i] = intArray[arraySize - 1 - i];
        }
        return result;
    }

    /**
     * 交换数组中两个数字位置
     * @param array
     * @param x
     * @param y
     */
    private static void swap(int[] array, int x, int y)
    {
        int temp = array[x];
        array[x] = array[y];
        array[y] = temp;
    }

    /**
     * 得到一个随机数int [min, max)
     * @param 最小随机数值
     * @param 最大随机数值
     * @return 获得的随机数int
     */
    public static int getRandomInt(int min, int max)
    {
        int result = min + new Double(Math.random() * (max - min)).intValue();
        return result;
    }

    /**
     * 得到一个随机字符
     * @return a random char with the range ASCII 33(!) to ASCII 126(~)
     */
    public static char getRandomChar()
    {
        // from ASCII code 33 to ASCII code 126
        int firstChar = 33; // "!"
        int lastChar = 126; // "~"
        char result = (char) (getRandomInt(firstChar, lastChar + 1));
        return result;
    }

    /**
     * 得到随机长度字符串
     * @param length the length of the String
     * @return a String filled with random char
     */
    public static String getRandomString(int length)
    {
        // include ASCII code from 33 to 126
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < length; i++)
        {
            result.append(getRandomChar());
        }
        return result.toString();
    }
}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值