Java實現的權重演算法(按權重展現廣告)_java

來源:互聯網
上載者:User

基本演算法描述如下:

1、每個廣告增加權重
2、將所有匹配廣告的權重相加sum,
3、以相加結果為隨機數的種子,產生1~sum之間的隨機數rd
4、.接著遍曆所有廣告,訪問順序可以隨意.將當前節點的權重值加上前面訪問的各節點權重值得curWt,判斷curWt >=  rd,如果條件成立則返回當前節點,如果不是則繼續累加下一節點. 直到符合上面的條件,由於rd<=sum 因此一定存在curWt>=rd。
特別說明:

此演算法和廣告的順序無關

import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;public class Test {  /**   * @param args   */  @SuppressWarnings("unchecked")  public static void main(String[] args) {        List<Node> arrNodes = new ArrayList<Node>();    Node n = new Node(10, "測試1");    arrNodes.add(n);    n = new Node(20, "測試2");    arrNodes.add(n);    n = new Node(30, "測試3");    arrNodes.add(n);    n = new Node(40, "測試4");    arrNodes.add(n);        //Collections.sort(arrNodes, new Node());    Map<String, Integer> showMap = null;    int sum = getSum(arrNodes);    int random = 0;    Node kw = null;    for(int k = 0; k < 20; k++) {      showMap = new LinkedHashMap<String, Integer>();      for(int i = 0; i < 100; i++) {        random = getRandom(sum);        kw = getKW(arrNodes, random);        if(showMap.containsKey(kw.kw)) {          showMap.put(kw.kw, showMap.get(kw.kw) + 1);        } else {          showMap.put(kw.kw, 1);        }        //System.out.println(i + " " +random + " " + getKW(arrNodes, random));      }      System.out.print(k + " ");      System.out.println(showMap);    }  }    public static Node getKW(List<Node> nodes, int rd) {    Node ret = null;    int curWt = 0;    for(Node n : nodes){      curWt += n.weight;      if(curWt >= rd) {        ret = n;        break;      }    }    return ret;  }  public static int getSum(List<Node> nodes) {    int sum = 0;    for(Node n : nodes)      sum += n.weight;    return sum;  }  public static int getRandom(int seed) {    return (int)Math.round(Math.random() * seed);  }}class Node implements Comparator{  int weight = 0;  String kw = "";    public Node() {}    public Node(int wt, String kw) {    this.weight = wt;    this.kw = kw;  }  public String toString(){    StringBuilder sbBuilder = new StringBuilder();    sbBuilder.append(" weight=").append(weight);    sbBuilder.append(" kw").append(kw);    return sbBuilder.toString();  }  public int compare(Object o1, Object o2) {    Node n1 = (Node)o1;    Node n2 = (Node)o2;    if(n1.weight > n2.weight)      return 1;    else       return 0;  }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.