1
\$\begingroup\$

Assuming I have a simple client-server game, where the server picks random players on a very frequent base, I was wondering what is the best way to select a random player (According to the following constraints):

  1. Solution must be high performance and highly scalable
  2. Random spread should be relatively even (meaning if I have 3 players and pick 99 times, they will all be picked 33 times more or less)
  3. Should only pick players who were active in the past X days (optional, but a big bonus)

The actual DB or data model used to store players isn't an issue here, as we'll select the technology in accordance to our needs.

However, high performance and scalability is (at the moment we have over 60,000 unique daily active players, and we plan on growing even more).

Thanks!

\$\endgroup\$
2
\$\begingroup\$

Select players from the database who fit your criteria (active in the past X days,) and put them into an array. Then use a good random number generator to generate a number in the range [0, 1], multiply that number by the size of your list, round the result, and use it to index into your list of users.

\$\endgroup\$
1
  • \$\begingroup\$ +1 sorting it in memory is much better than sorting it in the DB, and MT is quite good overall (but perhaps a bit overkill) \$\endgroup\$
    – ashes999
    May 26 '14 at 12:11
0
\$\begingroup\$

Since putting 60k player in an array just to select one of them sounds pretty dangerous to performance, you'd probably be best of with using your DB's inbuilt features.

If you are using SQL, then this code snippet will help you. You can easily add your third requirement (be active) by adding a WHERE-clause to the query.

Make sure to replace N by the size of your DB-table.

SELECT column FROM table
OFFSET RANDOM()*N
LIMIT 1
\$\endgroup\$
2
  • \$\begingroup\$ What makes you think this is better than an array? MySQL, for one, is well-known to have extremely poor performance for RANDOM. \$\endgroup\$
    – ashes999
    May 26 '14 at 12:09
  • \$\begingroup\$ Extracting 60000 rows out of a SQL database and constructing an array in your language to fill all of these rows in could be damaging performance depending on your choice of language. Furthermore, the author mentioned that he needs a scalable system: Imagine that the DB contains a few millions of players. Filling all of them into an array every few seconds would be extremely overkill. \$\endgroup\$ May 26 '14 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.