1. 程式人生 > >java根據概率隨機中獎 測試類

java根據概率隨機中獎 測試類

       最近要做一個寶箱抽獎的功能 自己先聯絡了一下,分別用 list和set 進行儲存和抽取,做了一個時間消耗的對比,感覺list應該比set讀取的要快些,但是這也不一定,希望大家能夠共同討論。

廢話少說上程式碼:

package com.test.testRandom;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;

/** 根據概率獲取獎品的測試類 */
public class TestRandom {

    public static void main(String[] args) {
	TestRandom tr = new TestRandom();
	// 用List隨機
	long begin = System.currentTimeMillis();
	for (int i = 0; i < 100; i++) {
	    tr.getGumByList();
	}
	System.out.println("list使用時間:" + (System.currentTimeMillis() - begin));
	// 用set隨機
	long begin1 = System.currentTimeMillis();
	for (int i = 0; i < 100; i++) {
	    tr.getGumBySet();
	}
	System.out.println("set使用時間:" + (System.currentTimeMillis() - begin1));
    }

    /* Set 獲取 */
    void getGumBySet() {
	int random = new Random().nextInt(100);
	int prizeRate = 0;// 中獎率
	Iterator<Gem> it = initSetGems().iterator();
	while (it.hasNext()) {
	    Gem gem = it.next();
	    prizeRate += gem.getPriority();
	    if (random < prizeRate) {
		System.out.println("獎品為:" + gem.getName() + "  概率:"
			+ gem.getPriority() + " 隨機數random:" + random
			+ " 概率基數prizeRate:" + prizeRate);
		break;
	    }
	}
    }

    /** List 獲取 */
    void getGumByList() {
	int random = new Random().nextInt(100);
	int prizeRate = 0;// 中獎率
	Iterator<Gem> it = initGems().iterator();
	while (it.hasNext()) {
	    Gem gem = it.next();
	    prizeRate += gem.getPriority();
	    if (random < prizeRate) {
		System.out.println("獎品為:" + gem.getName() + "  概率:"
			+ gem.getPriority() + " 隨機數random:" + random
			+ " 概率基數prizeRate:" + prizeRate);
		break;
	    }
	}
    }

    /** 初始化list */
    List<Gem> initGems() {
	List<Gem> gums = new ArrayList<Gem>();
	gums.add(new Gem("20", 20));
	gums.add(new Gem("7", 7));
	gums.add(new Gem("30", 30));
	gums.add(new Gem("24", 40));
	gums.add(new Gem("3", 3));
	return gums;
    }

    /** 初始化set */
    Set<Gem> initSetGems() {
	Set<Gem> gums = new HashSet<Gem>();
	gums.add(new Gem("20", 20));
	gums.add(new Gem("7", 7));
	gums.add(new Gem("30", 30));
	gums.add(new Gem("24", 40));
	gums.add(new Gem("3", 3));
	return gums;
    }

    /**獎品類*/
    class Gem {
	/** 獎品名稱 */
	private String name;
	/** 獎品概率 */
	private int priority;

	public Gem() {
	    super();
	}

	public Gem(String name, int priority) {
	    super();
	    this.name = name;
	    this.priority = priority;
	}

	@Override
	public String toString() {
	    return "Gum [name=" + name + ", priority=" + priority + "]";
	}
	public String getName() {
	    return name;
	}

	public void setName(String name) {
	    this.name = name;
	}
	public int getPriority() {
	    return priority;
	}
	public void setPriority(int priority) {
	    this.priority = priority;
	}

    }
}