# Server side random selection of players

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!

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.

• +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) May 26 '14 at 12:11

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

• What makes you think this is better than an array? MySQL, for one, is well-known to have extremely poor performance for RANDOM. May 26 '14 at 12:09
• 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. May 26 '14 at 13:33