Justtechjobs.com Find a programming school near you






Online Campus Both


php-db | 2001062

Re: [PHP-DB] most efficient weighting system? URGENT From: Hugh Bothwell (hugh_bothwell <email protected>)
Date: 06/29/01

How many rows are you likely to have, and how dynamic are the weights?

I think I'd add a "cumulative sum" column to your table, ie

id weight cum_weight
1 10 10
2 5 15
3 3 18
4 20 38
5 2 40

then
$query = "SELECT id FROM table WHERE cum_weight >= ".rand(1,40)." ORDER BY
cum_weight LIMIT 1";

Note that if you delete or update any row, the cumulative values become
incorrect. It would be better to calculate cum_weight dynamically, but I'm
not sure how; also, this could be computationally expensive.

Another way to do this would be to repeat each row the appropriate number of
times, ie

id value
1 1
2 1
3 1
...
10 1
11 2
12 2
...
15 2
16 3
17 3
18 3
19 4
20 4
...
37 4
38 4
etc.

Then you could use
$query = "SELECT value FROM table ORDER BY RAND() LIMIT 1";

""Noah Spitzer-Williams"" <noahsw <email protected>> wrote in message
news:9hilnk$9pp$1 <email protected>
> if i have several rows in a table and i want some to have certain weights
> what is the best way to pick a random row based on its weight?
>
> ex of table:
> id weight
> 1 10
> 2 5
> 3 3
> 4 20
> 5 2
>
> therefore, since there is a total weight of 40, id 1 should be picked 25%
> (10/40) of the time, id 4 50% (20/40), etc...
>
> what is the best way to do this?

-- 
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, e-mail: php-db-unsubscribe <email protected>
For additional commands, e-mail: php-db-help <email protected>
To contact the list administrators, e-mail: php-list-admin <email protected>