现在的位置: 首页 > 综合 > 正文

java 随机数 随机打乱数组 随机抽取

2017年12月01日 ⁄ 综合 ⁄ 共 1656字 ⁄ 字号 评论关闭

        最近做项目遇到一些随机数,随机打乱数组等关于随机处理的问题,今天做一个总结。

1.给出一个生成指定长度的随机密码代码,代码如下:

import java.util.Random;

public class test {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(genRandomNum(10));
	}

	/**
	 * 生成随即密码
	 * 
	 * @param pwd_len
	 *            生成的密码的总长度
	 * @return 密码的字符串
	 */
	public static String genRandomNum(int pwd_len) {
		// 35是因为数组是从0开始的,26个字母+10个数字
		final int maxNum = 36;
		int i; // 生成的随机数
		int count = 0; // 生成的密码的长度
		char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 
				'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 
				'0', '1', '2', '3', '4', '5', '6', '7', '8','9' };

		StringBuffer pwd = new StringBuffer("");
		Random r = new Random();
		while (count < pwd_len) {
			// 生成随机数,取绝对值,防止生成负数,
			i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1

			if (i >= 0 && i < str.length) {
				pwd.append(str[i]);
				count++;
			}
		}

		return pwd.toString();
	}
}

2.打乱一个数组的顺序,生成随机数组,这里要借助于java的工具Collections中的shuffle()方法。代码如下:

/**
 *  随即打乱一个顺序的数组
 */
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;


public class Shuffle {
	
	public static void main(String[] args) {
		shuffle();
	}
	
	public static void shuffle(){
		int[] x = {1,2,3,4,5,6,7,8,9};
		List list = new ArrayList();
		for(int i = 0;i < x.length;i++){
			System.out.print(x[i]+", ");
			list.add(x[i]);
		}
		System.out.println();
		
		Collections.shuffle(list);
		
		Iterator ite = list.iterator();
		while(ite.hasNext()){
			System.out.print(ite.next().toString()+", ");
		}
	}
}

3.随机从数组中取出指定的不重复的n个数,代码如下:

/**
   * Description: 随机从数组中取出指定的不重复的n个数。
   * @param ArrayList 原始数组
   * @param int n 随机抽取的个数
   * @return 返回抽取的数组
   */
public static ArrayList getRandomArray(ArrayList  list ,int num)
{
     ArrayList aList=new ArrayList();
      for(int  i =0 ; i<num ; i++)
       {
          int randomNum=getRandom(list.size());
           aList.add(list.get(randomNum));
           list.remove(randomNum);
       }
return aList
}

好了,先写这么多,再遇到“随机”问题的话再更新。

抱歉!评论已关闭.