随机从数组或集合中抽取一个值或 从list集合中随机抽几个值 或算权重

118 篇文章 2 订阅
26 篇文章 0 订阅

直接上代码

package cn.itcast.jk.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName ArraysUtils
 * @Description: 数组工具类
 * @author: GuXiYang
 * @date: 2017/04/29 16:43:00
 */
public class ArraysUtils {
	/**
	 * @Description:去除空格
	 * @author: GuXiYang
	 * @date: 2015-10-12 下午4:18:59
	 * @param str
	 * @return
	 */
	public static String getStringNoBlank(String str) {
		if (str != null && !"".equals(str)) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			String strNoBlank = m.replaceAll("");
			return strNoBlank;
		} else {
			return str;
		}
	}

	/**
	 * @Description: 判断数组中是否包含某个值
	 * @author: GuXiYang
	 * @date: 2015-9-25 下午2:32:50
	 * @param arr
	 * @param targetValue
	 * @see D瓜哥,http://www.diguage.com/
	 * @return
	 */
	public static boolean useList(String[] arr, String targetValue) {
		return Arrays.asList(arr).contains(targetValue);
	}

	/**
	 * Coder:D瓜哥,http://www.diguage.com/
	 */
	public static boolean useSet(String[] arr, String targetValue) {
		Set<String> set = new HashSet<String>(Arrays.asList(arr));
		return set.contains(targetValue);
	}

	/**
	 * Coder:D瓜哥,http://www.diguage.com/
	 */
	public static boolean useLoop(String[] arr, String targetValue) {
		for (String s : arr) {
			if (s.equals(targetValue)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @Description: 判断map中是否包含指定的key
	 * @author: GuXiYang
	 * @date: 2015-11-17 下午3:48:27
	 * @param map
	 * @param key
	 * @return true/false
	 */
	public static boolean vidateKey(Map map, String key) {
		return map.containsKey(key);
	}

	/**
	 * @Description: 验证对象是不是数组
	 * @author: GuXiYang
	 * @date: 2017/04/29 16:48:38
	 * @param obj
	 * @return
	 */
	public static boolean isArray(Object obj) {
		return (obj != null && obj.getClass().isArray());
	}

	/**
	 * @Description: 判断数组是否为空
	 * @author: GuXiYang
	 * @date: 2017/04/29 16:49:15
	 * @param array
	 *            数组
	 * @return true/false
	 */
	public static boolean isEmpty(Object[] array) {
		return (array == null || array.length == 0);
	}

	/**
	 * Determine if the given objects are equal, returning {@code true} if both
	 * are {@code null} or {@code false} if only one is {@code null}.
	 * <p>
	 * Compares arrays with {@code Arrays.equals}, performing an equality check
	 * based on the array elements rather than the array reference.
	 * 
	 * @param o1
	 *            first Object to compare
	 * @param o2
	 *            second Object to compare
	 * @return whether the given objects are equal
	 * @see java.util.Arrays#equals
	 */
	public static boolean nullSafeEquals(Object o1, Object o2) {
		if (o1 == o2) {
			return true;
		}
		if (o1 == null || o2 == null) {
			return false;
		}
		if (o1.equals(o2)) {
			return true;
		}
		if (o1.getClass().isArray() && o2.getClass().isArray()) {
			if (o1 instanceof Object[] && o2 instanceof Object[]) {
				return Arrays.equals((Object[]) o1, (Object[]) o2);
			}
			if (o1 instanceof boolean[] && o2 instanceof boolean[]) {
				return Arrays.equals((boolean[]) o1, (boolean[]) o2);
			}
			if (o1 instanceof byte[] && o2 instanceof byte[]) {
				return Arrays.equals((byte[]) o1, (byte[]) o2);
			}
			if (o1 instanceof char[] && o2 instanceof char[]) {
				return Arrays.equals((char[]) o1, (char[]) o2);
			}
			if (o1 instanceof double[] && o2 instanceof double[]) {
				return Arrays.equals((double[]) o1, (double[]) o2);
			}
			if (o1 instanceof float[] && o2 instanceof float[]) {
				return Arrays.equals((float[]) o1, (float[]) o2);
			}
			if (o1 instanceof int[] && o2 instanceof int[]) {
				return Arrays.equals((int[]) o1, (int[]) o2);
			}
			if (o1 instanceof long[] && o2 instanceof long[]) {
				return Arrays.equals((long[]) o1, (long[]) o2);
			}
			if (o1 instanceof short[] && o2 instanceof short[]) {
				return Arrays.equals((short[]) o1, (short[]) o2);
			}
		}
		return false;
	}

	/**
	 * @Description: 验证数组是否包括元素
	 * @author: GuXiYang
	 * @date: 2017/04/29 16:50:23
	 * @param array
	 *            数组
	 * @param element
	 *            元素
	 * @return
	 */
	public static boolean containsElement(Object[] array, Object element) {
		if (array == null) {
			return false;
		}
		for (Object arrayEle : array) {
			if (nullSafeEquals(arrayEle, element)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Check whether the given array of enum constants contains a constant with
	 * the given name.
	 * 
	 * @param enumValues
	 *            the enum values to check, typically the product of a call to
	 *            MyEnum.values()
	 * @param constant
	 *            the constant name to find (must not be null or empty string)
	 * @param caseSensitive
	 *            whether case is significant in determining a match
	 * @return whether the constant has been found in the given array
	 *         判断枚举数组中是否包含某个字符串
	 */
	public static boolean containsConstant(Enum<?>[] enumValues,
			String constant, boolean caseSensitive) {
		for (Enum<?> candidate : enumValues) {
			if (caseSensitive ? candidate.toString().equals(constant)
					: candidate.toString().equalsIgnoreCase(constant)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Check whether the given array of enum constants contains a constant with
	 * the given name, ignoring case when determining a match.
	 * 
	 * @param enumValues
	 *            the enum values to check, typically the product of a call to
	 *            MyEnum.values()
	 * @param constant
	 *            the constant name to find (must not be null or empty string)
	 * @return whether the constant has been found in the given array
	 *         判断枚举数组中是否包含某个字符串(忽略大小写)
	 */
	public static boolean containsConstant(Enum<?>[] enumValues, String constant) {
		return containsConstant(enumValues, constant, false);
	}

	/**
	 * Case insensitive alternative to {@link Enum#valueOf(Class, String)}.
	 * 
	 * @param <E>
	 *            the concrete Enum type
	 * @param enumValues
	 *            the array of all Enum constants in question, usually per
	 *            Enum.values()
	 * @param constant
	 *            the constant to get the enum value of
	 * @throws IllegalArgumentException
	 *             if the given constant is not found in the given array of enum
	 *             values. Use {@link #containsConstant(Enum[], String)} as a
	 *             guard to avoid this exception.
	 */
	public static <E extends Enum<?>> E caseInsensitiveValueOf(E[] enumValues,
			String constant) {
		for (E candidate : enumValues) {
			if (candidate.toString().equalsIgnoreCase(constant)) {
				return candidate;
			}
		}
		throw new IllegalArgumentException(String.format(
				"constant [%s] does not exist in enum type %s", constant,
				enumValues.getClass().getComponentType().getName()));
	}
}


package com.test.springtest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;

import cn.itcast.jk.util.ArraysUtils;

public class ListTest {
	// 获取当前时间 从当前时间往前推七天 获取到这七天的日期 添加到集合里面

	private ArrayList<String> xValues = new ArrayList<String>();

	// private ArrayList<HealthHelper> helpers = new ArrayList<HealthHelper>();

	// 传入的是当前的时间
	private void getdate(String a) {
		try {
			for (int i = 7; i > 0; i--) {
				SimpleDateFormat sdf = new SimpleDateFormat("MM.dd");
				String w = a;
				Date date = sdf.parse(w);
				Calendar calendar = new GregorianCalendar();
				calendar.setTime(date);
				calendar.add(calendar.DATE, -i);// 把日期往后增加一天.整数往后推,负数往前移动
				date = calendar.getTime(); // 这个时间就是日期往后推一天的结果
				String DateString = sdf.format(date);
				xValues.add(DateString);
			}

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	/**
	 * @Description: 从数组中随机获取值
	 * @author: GuXiYang
	 * @date: 2017/04/29 16:57:30
	 * @param arrs 数组
	 * @return 值
	 */
	private static int getArrayRand(Object[]  arrs){
		if (ArraysUtils.isEmpty(arrs)) {
			return 0;
		}
		//产生0-(arr.length-1)的整数值,也是数组的索引
		int index=(int)(Math.random()*arrs.length);
		System.out.println("随机数_索引:"+index);
		//		return (int) arrs[index];

		int rand = (int) arrs[index];
		System.out.println("值:"+rand);
		return rand;
		//		
		//		for (int i = 0; i < 5; i++) {
		//			System.out.println(Math.random()*arrs.length);
		//		}

		//	

	}

	/**
	 * @Description: 随机抽取集合中值
	 * @author: GuXiYang
	 * @date: 2017/04/29 17:12:00
	 * @param list
	 */
	private static  void getListArr(List<Object> list){
		if(list.isEmpty()){
			return ;
		}
		Random ran = new Random();
		//产生0-(list.size())个随机数 也就是集合下标	
		int con=ran.nextInt(list.size());
		String result=list.get(con).toString();
		System.out.println("随机下标:"+con+" 值:"+result);	
	}


	// 从List中随机出count个对象  
	private static List<Object> randomTopic(List<Object> list, int count) {  
		// 创建一个长度为count(count<=list)的数组,用于存随机数  
		int[] a = new int[count];  
		// 利于此数组产生随机数  
		int[] b = new int[list.size()];  
		int size = list.size();  

		// 取样填充至数组a满  
		for (int i = 0; i < count; i++) {  
			int num = (int) (Math.random() * size); // [0,size)  
			int where = -1;  
			for (int j = 0; j < b.length; j++) {  
				if (b[j] != -1) {  
					where++;  
					if (where == num) {  
						b[j] = -1;  
						a[i] = j;  
					}  
				}  
			}  
			size = size - 1;  
		}  
		// a填满后 将数据加载到rslist  
		List<Object> rslist = new ArrayList<Object>();  
		for (int i = 0; i < count; i++) {  
			Object df = (Object) list.get(a[i]);  
			rslist.add(df);  
		}  
		return rslist;  
	}  



	public static void main(String[] args) {

		Object[] arr = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};

		System.out.println(getArrayRand(arr));


		// List.remove( Math.random()*(List.size()-1));
		//		java 从读取表数据的list中随机获取一个值 
		List<Object> list=new ArrayList<Object>();
		list.add("一");
		list.add("切");
		list.add("只");
		list.add("能");
		list.add("靠");
		list.add("自");
		list.add("己");


		getListArr(list);


		//		for (int i = 0; i <10; i++) {
		//
		//			Random ran = new Random();
		//			//产生0-(list.size())个随机数	
		//			int con=ran.nextInt(list.size());
		//			System.out.println("11====="+con);
		//			System.out.println(con+"-----===="+list.get(con).toString());

		//		System.out.println(ran.nextInt()+"---"+ran.nextInt(list.size())+"-----"+list.get(ran.nextInt(list.size())).toString());
		//		System.out.println(ran.nextInt(list.size()));
		//		System.out.println(list.get(ran.nextInt(list.size())).toString());

		//		}

		//从list中随机抽取几个集合
		List<Object> l=	randomTopic(list,3);
		for (Object o:l) {
			System.out.println(o);
		}

	}
}



package com.test.springtest;

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

public class WeightRandom {    
	static List<WeightCategory>  categorys = new ArrayList<WeightCategory>();    
	private static Random random = new Random();    

	public static void initData() {    
		WeightCategory wc1 = new WeightCategory("A",20);    
		WeightCategory wc2 = new WeightCategory("B",30);    
		WeightCategory wc3 = new WeightCategory("C",10);    
		WeightCategory wc4 = new WeightCategory("D",5);    
		WeightCategory wc5 = new WeightCategory("E",35);    
		categorys.add(wc1);    
		categorys.add(wc2);    
		categorys.add(wc3);    
		categorys.add(wc4);    
		categorys.add(wc5);    
	}    

	public static void main(String[] args) {    
		initData();    
		Integer weightSum = 0;    
		for (WeightCategory wc : categorys) {    
			weightSum += wc.getWeight();    
		}    
		System.out.println("权重数:"+weightSum);

		if (weightSum <= 0) {    
			System.err.println("Error: weightSum=" + weightSum.toString());    
			return;    
		}    
		Integer n = random.nextInt(weightSum); // n in [0, weightSum)    
		System.out.println("产生随机数:"+n);
		Integer m = 0;    
		for (WeightCategory wc : categorys) {    
			if (m <= n && n < m + wc.getWeight()) {    
				System.out.println("This Random Category is "+wc.getCategory());    
				break;    
			}    
			m += wc.getWeight();    
		}    


	}    

}    

class WeightCategory {    
	private String category;    
	private Integer weight;    


	public WeightCategory() {    
		super();    
	}    

	public WeightCategory(String category, Integer weight) {    
		super();    
		this.setCategory(category);    
		this.setWeight(weight);    
	}    


	public Integer getWeight() {    
		return weight;    
	}    

	public void setWeight(Integer weight) {    
		this.weight = weight;    
	}    

	public String getCategory() {    
		return category;    
	}    

	public void setCategory(String category) {    
		this.category = category;    
	}    
}    





package com.test.springtest;

import java.math.BigDecimal;

import org.junit.Test;

/**
 * 
 * @ClassName HongBao
 * @Description:发红包
 * @author: GuXiYang
 * @date: 2017/04/29 16:29:02
 */
public class HongBao {

	/**
	 * 
	 * @Description: 红包参数
	 * @author: GuXiYang
	 * @date: 2017/04/29 16:29:33
	 * @param total
	 *            红包总额
	 * @param num
	 *            红包数
	 * @param min
	 *            最小红包
	 */
	void hb(double total, int num, double min) {

		for (int i = 1; i < num; i++) {

			double safe_total = (total - (num - i) * min) / (num - i);

			double money = Math.random() * (safe_total - min) + min;

			BigDecimal money_bd = new BigDecimal(money);

			money = money_bd.setScale(2, BigDecimal.ROUND_HALF_UP)
					.doubleValue();

			total = total - money;

			BigDecimal total_bd = new BigDecimal(total);

			total = total_bd.setScale(2, BigDecimal.ROUND_HALF_UP)
					.doubleValue();

			System.out
					.println("第" + i + "个红包:" + money + ",余额为:" + total + "元");

		}

		System.out.println("第" + num + "个红包:" + total + ",余额为:0元");

	}

	void zb() {

		for (int a = 0; a <= 10000; a++) {

			if (a % 1000 == 0)

				System.out.println(a);

		}

	}

	/**
	 * @Description:测试
	 * @author: GuXiYang
	 * @date: 2017/04/29 16:30:53
	 */
	@Test
	public void testHonbao() {

		hb(100, 9, 0.01);// 金额,个数,最少值

		// zb();

	}

}




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值