權重隨機算法的java實現

來源:文萃谷 2.51W

本文實例講述了Java權重隨機的實現方法。分享給大家供大家參考。具體分析如下:

權重隨機算法的java實現

權重隨機在項目中經常用到,所以我把它抽象到一個工具類中。

一般實現隨機權重有兩種方式:

1. 使用一個數組存放權重對應的實際目標,比如A的權重是2,B的'權重是3,那麼數組長度為5, 數組前兩個存放A,後三個存放B。

然後隨機一個[0-數據長度)的數字,直接取數組對應下標的值就可以了。

優點:數據結構簡單,算法高效,實現簡單

缺點:當權重值比較大同時數據又比較多的時候,會浪費內存

2. 使用區間算法,從前到後依次疊加權重,然後隨機一個[1-權重和]的數字,再用隨機的權重依次減去每個元素的權重,當第一個小於等於0的元素就是我們找元素

這裏實現可以借用Arrays的binarySearch方法。

完整實例代碼點擊此處本站下載。

貼一下代碼:

複製代碼 代碼如下:/**

* 建議使用RandomUtil類創建RandomMeta對象

* @author wxf on 14-5-5.

*/

public class WeightMeta{

private final Random ran = new Random();

private final T[] nodes;

private final int[] weights;

private final int maxW;

public WeightMeta(T[] nodes, int[] weights) {

s = nodes;

hts = weights;

= weights[th - 1];

}

/**

* 該方法返回權重隨機對象

* @return

*/

public T random() {

int index = rySearch(weights, Int(maxW) + 1);

if (index < 0) {

index = -1 - index;

}

return nodes[index];

}

public T random(int ranInt) {

if (ranInt > maxW) {

ranInt = maxW;

} else if(ranInt < 0){

ranInt = 1;

} else {

ranInt ++;

}

int index = rySearch(weights, ranInt);

if (index < 0) {

index = -1 - index;

}

return nodes[index];

}

@Override

public String toString() {

StringBuilder l1 = new StringBuilder();

StringBuilder l2 = new StringBuilder("[random]t");

StringBuilder l3 = new StringBuilder("[node]tt");

nd(lass()ame())nd(":")nd(Code())nd(":n")nd("[index]tt");

for (int i = 0; i < th; i++) {

nd(i)nd("t");

nd(weights[i])nd("t");

nd(nodes[i])nd("t");

nd("n");

nd("n");

nd("n");

return nd(l2)nd(l3)ring();

複製代碼 代碼如下:/**

* 隨機工具類

* 使用權重的集合Map構建隨機元數據對象

* 比如:

* 我們有3個url地址,他們的權重分別為1,2,3現在我們利用RandomUtil來根據權重隨機獲取url:

* (url1, 1);

* (url2, 2);

* (url3, 3);

* RandomMetamd = dWeightMeta(map);

* String weightRandomUrl = om();

* @author wxf on 14-5-5.

*/

public class RandomUtil {

public staticWeightMetabuildWeightMeta(final MapweightMap) {

final int size = ();

Object[] nodes = new Object[size];

int[] weights = new int[size];

int index = 0;

int weightAdder = 0;

for (yeach : ySet()) {

nodes[index] = ey();

weights[index++] = (weightAdder = weightAdder + alue());

}

return new WeightMeta((T[]) nodes, weights);

}

}

希望本文所述對大家的Java程序設計有所幫助。

熱門標籤