# Weighted Random Record???? - Coldfusion - Advanced Techniques

Guys, Good morning.... I have a random script I am using to pull a random row.... <cfset displayRow = randrange(1,randompic.recordCount)> <cfoutput>#randompic.mlocation[displayRow]#</cfoutput> ..... However, I want to make this a weighted formula. In other words, one of the records in my query has a better chance of appearing than another. Any ideas?...

1. ## Weighted Random Record????

Guys,
Good morning.... I have a random script I am using to pull a random row....

<cfset displayRow = randrange(1,randompic.recordCount)>

<cfoutput>#randompic.mlocation[displayRow]#</cfoutput>

.....
However, I want to make this a weighted formula. In other words, one of the
records in my query has a better chance of appearing than another. Any ideas?

johnegbert Guest

2. ## Re: Weighted Random Record????

Depending on where else that database table is used, and what constraints you
have on the table, the easiest thing to do would be to just duplicate the row
you want weighted more.

Whether this is the best method will depend on how else that table is used,
etc.

Kronin555 Guest

3. ## Re: Weighted Random Record????

Kronin555
thanks man for takin a shot, thats not exactly what I am trying to do... I
already have a field in the table called weight.... I am going to set it so
that it can be like an integer, 1, 2, 3 ,4 ,5 .... depending on how much weight
i want it to have... so like 1 would be less likely to get picked, but 5 would
be much more likely.. i know there has to be some sort of multiplication
algorithm, but I cant figure it out.......
Someone help me with this? Anyone else have ideas?

johnegbert Guest

4. ## Re: Weighted Random Record????

Same thing, as it was already desribed by Kronin. You have to physycally or
logically add duplicate records according to their weights.

1. Find total sum of weights in the recordset. Good idea to remember array of
running totals (will be needed).
2. Generate random number between 1 and the total.
3. First record that has running weight total greater or equal to the
generated number is the one.

Example:

rec weight total
=============
1 1 1
2 2 3
3 2 5
4 3 8 <------ 6
5 1 9

random number (1,9) is 6 (well, not always):

1 2 2 3 3 4 4 4 5 record # is 4
^

Mr Guest

#### Posting Permissions

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