Algorithm to pick user
I need an algorithm for picking a user.
Users are identified by letter {A, B, C, ...} and are ranked by number {1,
2, 3, ...}. Rank is the degree of likelihood to be picked, so a rank 2
user is twice as likely to be picked over a rank 1 user, and rank 4 is
four times as likely, etc.
So let's say four users are {A, B, C, D}, with rank {1, 1, 5, 2}
respectively. A user table might store rank:
USER RANK
A 1
B 1
C 5
D 2
How do I pick a user based on rank?
My first idea for an algorithm is to add up all the ranks 1 + 1 + 5 + 2 to
obtain a sum of 9. Then assign subranges from 1 to 9 to each user, where
subrange size is user rank. So A has range [1, 1], B has range [2, 2], C
has range [3, 7] (5 possibilities due to rank being 5), and D has range
[8, 9]. The table becomes this:
USER RANK RANGE
A 1 [1, 1]
B 1 [2, 2]
C 5 [3, 7]
D 2 [8, 9]
Then calculate a random value from 1 to 9, and find the user whose range
contains that value. So if the random value is 4, user C is picked because
4 falls within range [3, 7].
This achieves fairness based on rank. If you repeat picking randomly this
way, on the average, users will be chosen fairly, and no user will be
starved.
However, it feels sloppy, because to add or remove users, I have to
recalculate all the ranges. Here is removing user C (recalculate range of
user D):
USER RANK RANGE
A 1 [1, 1]
B 1 [2, 2]
D 2 [3, 4]
And here is changing user A to have rank 2 (recalculate range of B and D):
USER RANK RANGE
A 2 [1, 2]
B 1 [3, 3]
D 2 [4, 5]
What is the best algorithm to pick a user? Surely recalculating ranges for
every user add, delete, or update is suboptimal. Is there a well-known
function or algorithm that can help?
No comments:
Post a Comment