設定された確率に基づいてコンテンツをランダムに表示するアルゴリズム


もし私たちがウェブページの上のある位置に一連の広告を表示するとしたら、一定の規則に従って、例えば与えられた広告費用のいくら、私たちは異なる広告に対して相応の表示確率を設定して、このようにユーザーはウェブページを閲覧する時、設定した数率に従ってすぐに広告内容を表示します.次のアルゴリズムはこのランダムに内容を選択する機能を実現し、このアルゴリズムの最適化を歓迎します.
/**
 * @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
... ...