SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot JordanTLClive's Avatar
    Join Date
    Feb 2001
    Location
    Las Vegas, NV
    Posts
    118
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Weighted Random Picking

    I'm building a site that needs to be able to pick semi-randomly from the database. What I need to do is pick a row from the database, have it be semi-random, but in general favor results which have a lower count value. The count value is increased each time that row is picked. Additionally, I need to not pick the same row more than once per session. I just cant seem to decide on the most efficient way of going about doing this, so if anyone has a thought, I'm listening. Thanks:-D
    -Jordan

  2. #2
    Non-Member Pejone's Avatar
    Join Date
    Dec 2002
    Location
    /ua/houston/
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    $QUERY=MYSQL_QUERY("SELECT * FROM `tablename` BY rand() LIMIT 1"); 


    save id of record in sesion var. and at next time whan you will need rendom query add


    PHP Code:
    WHERE `id` < '$SESID' 

  3. #3
    SitePoint Evangelist
    Join Date
    Nov 2001
    Location
    UK
    Posts
    466
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    using your approach would require a few queries - an output array, a rand numeric and a last query

    query - select max(count)
    $tmp = 0;
    while(query = select id,count)
    {
    $array[ id ] = $tmp+($max - $count);
    $tmp += $max-$count;
    }
    $rand = rand(0,$tmp);
    foreach($array AS $key=>$val)
    {
    $pull_row = ($val < $rand) ? $key : $pull_row;
    }
    query = select * from .. where id='$pull_row'

    very long winded.

    Perhaps a better approach would be just to pull the minimum 'count' and then get a rand() from those results

    $min = query - select MIN(count) AS min_count
    $get_row = select * WHERE count=$min_count ORDER BY rand() LIMIT 1

    pseudo code - amend to suit
    teckis - that's news to me.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •