根据设定好的几率来随机显示内容的算法

xiaoxiao2026-05-24  11

假设我们要在网页上的某个位置显示一系列的广告,按照一定的规则,比如给的广告费用的多少,我们对不同的广告都设定了相应的显示几率,这样用户在浏览网页的时候,就会按照设定好的几率随即显示广告内容。下面的算法实现了这个随机选取内容的功能,欢迎大家优化这个算法。

/** * @author Tracy.Zhang * */ public class Random { /** * 四个广告A,B,C,D. */ private String choices[] = { "A", "B", "C", "D" }; /** * 每个广告对应的几率 */ private int rates[] = { 10, 20, 30, 40 }; /** * 数轴 */ private List<Integer> list = new ArrayList<Integer>(); /** * 计算数轴上的点 * @param j * @return */ private int getRandomRate(int j) { int rate = 0; for (int i = 0; i < j; i++) { rate = rate + rates[i]; } return rate; } /** * 构造一个数轴,每个选项对应一个区间 */ private void init() { list.add(0); for (int i = 0; i < choices.length; i++) { list.add(getRandomRate(i + 1)); } } /** * 使用Math 的random 方法产生一个0--100 的随机数种子, * 判断其落在那个区间上.返回该区间对应的广告. * @return */ public String getChoice() { init(); String choice = ""; int random = (int) (100 * Math.random()); for (int i = 0; i < choices.length; i++) { if (list.get(i) <= random && random < list.get(i + 1)) { choice = choices[i]; break; } } return choice; } }

 以下是相应的测试用例:

public class RandomTest { @Test public void testGetRate() { Random ran = new Random(); String tempChoice = ""; int total = 100000; int a = 0; int b = 0; int c = 0; int d = 0; for (int i = 0; i < total; i++) { tempChoice = ran.getChoice(); if("A".equals(tempChoice)){ a++; }else if("B".equals(tempChoice)){ b++; } else if("C".equals(tempChoice)){ c++; } else if("D".equals(tempChoice)){ d++; } } System.out.print("Total="+total+" Rating:A="+a+":B="+b+":C="+c+":D="+d); } @Test public void testGetRandom1() { Random ran = new Random(); System.out.print(ran.getChoice()); } }

 

测试结果,

Total=100000 Rating:A=10087:B=19780:C=30060:D=40073

Total=50000 Rating:A=5024:B=10038:C=15071:D=19867

... ...

转载请注明原文地址: https://www.6miu.com/read-5049325.html

最新回复(0)