From 37efb139eefe5da374701c9c1669d1e38aba38f3 Mon Sep 17 00:00:00 2001 From: Mark Tearle Date: Sat, 13 Dec 2014 21:00:48 +0800 Subject: [PATCH] Modify idler selection algorithm --- VendServer/VendServer.py | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/VendServer/VendServer.py b/VendServer/VendServer.py index a009da7..0962697 100755 --- a/VendServer/VendServer.py +++ b/VendServer/VendServer.py @@ -288,23 +288,33 @@ def reset_idler(v, vstatus, t = None): def choose_idler(): global idlers, idler - iiindex = 0 - average_affinity = 10 # guessing here... - if idler and idler.__class__ != GreetingIdler: - iiindex = idlers.index(idler) - - iilen = len(idlers) - - move = int(random()*len(idlers)*average_affinity) + 1 + # Implementation of the King Of the Hill algorithm from; + # http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/ + + #def weighted_choice_king(weights): + # total = 0 + # winner = 0 + # for i, w in enumerate(weights): + # total += w + # if random.random() * total < w: + # winner = i + # return winner + # + + total = 0 + winner = None + + for choice in idlers: + weight = choice.affinity() + total += weight + if random() * total < weight: + winner = choice - while move >= 0: - iiindex += 1 - iiindex %= iilen - idler = idlers[iiindex] - move -= idler.affinity() + idler = winner - idler.reset() + if idler: + idler.reset() def idle_step(vstatus): global idler -- 2.20.1