The basic algorithms are described as follows:
1, each advertisement increases the weight
2, the weight of all matching ads added sum,
3, to add the result of the random number of seeds, generate 1~sum between the random number Rd
4. Then iterate through all the ads, access order can be arbitrary. The weight of the current node plus the previous access to the weight of each node is worth CURWT, Judge Curwt >= Rd, if the condition is set to return the current node, if not then continue to accumulate the next node. Until the above conditions are met, due to rd<=sum there must be curwt>=rd.
Special Note:
This algorithm has nothing to do with the order of the ads
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, "Test 1");
Arrnodes.add (n);
n = new Node (20, "Test 2");
Arrnodes.add (n);
n = new Node (30, "Test 3");
Arrnodes.add (n);
n = new Node (40, "Test 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 < k++) {Showmap = new linkedhashmap<string, integer> ();
for (int i = 0; i < 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;
}
}