java 抽奖权重概率实现

主要代码如下
此代码可以拓展使用,比如
WeightCategory 新增其他字段, 等被抽中时候获取显示其中的某个参数,如奖品说明
initData()的数据可以读取数据库的奖项设置,用for循环添加

package test;

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 int a =0;
	public static int b = 0;
	public static int c = 0;
	public static int d =0;

	public static void initData() {
		WeightCategory wc1 = new WeightCategory(1, "一等奖", 60);
		WeightCategory wc2 = new WeightCategory(2, "二等奖", 20);
		WeightCategory wc3 = new WeightCategory(3, "三等奖", 10);
		WeightCategory wc4 = new WeightCategory(4, "四等奖", 10);
		categorys.add(wc1);
		categorys.add(wc2);
		categorys.add(wc3);
		categorys.add(wc4);
	}

	public static void main(String[] args) {
		// 循环100次 看下权重效果
		for (int i = 0; i < 100; i++) {
			mainWeightRandom();
		}
		
		System.out.println("a被抽:" + a);
		System.out.println("b被抽:" + b);
		System.out.println("c被抽:" + c);
		System.out.println("d被抽:" + d);
	}
	
	// 权重主方法
	public static void mainWeightRandom() {
		initData();
		Integer weightSum = 0;
		for (WeightCategory wc : categorys) {
			weightSum += wc.getWeight();
		}

		if (weightSum <= 0) {
			System.err.println("Error: weightSum=" + weightSum.toString());
			return;
		}
		Integer n = random.nextInt(weightSum); // n in [0, weightSum)
		Integer m = 0;
		for (WeightCategory wc : categorys) {
			if (m <= n && n < m + wc.getWeight()) {
				System.out.println("你抽中了: " + wc.getCategory());
				if (wc.getNum() == 1) {
					a+=1;
				}
				if (wc.getNum() == 2) {
					b+=1;
				}
				if (wc.getNum() == 3) {
					c+=1;
				}
				if (wc.getNum() == 4) {
					d+=1;
				}
				break;
			}
			m += wc.getWeight();
		}
	}

}

class WeightCategory {
	private Integer num; // 奖品编号
	private String category; // 奖项名称
	private Integer weight; // 权重(抽中概率)

	public WeightCategory() {
		super();
	}

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

	public Integer getNum() {
		return num;
	}

	public void setNum(Integer num) {
		this.num = num;
	}
	
	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;
	}
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值