Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hi Anyone know how to randomize

Status
Not open for further replies.

nsampson1

IS-IT--Management
Sep 8, 2000
26
GB
Hi

Anyone know how to randomize a comma delimited list in coldfusion?

eg "1,2,3,4,5,6,7,8,9" into "4,7,3,2,5,1,8,9,6"


thanks in advance

Neil

 
This will get random values from yuor list. The only problem being is that it will return duplicate enteries.

given a list: 1,2,3,4,5,6,7

this will return 3,3,7,6,6,4

but this is the basic way to get random values from a list!

<CFSET randList = &quot;&quot;>

<CFLOOP INDEX=&quot;i&quot; LIST=&quot;#bList#&quot; DELIMITERS=&quot;,&quot;>
<CFSET randPos = RandRange(1,ListLen(bList))>
<CFSET randVal = ListGetAt(bList,randPos)>
<CFSET randList = ListAppend(randList,randVal)>
</CFLOOP>

hope this helps !
 
thanks for the suggestion arperry

sadly, I need to avoid duplicates in my random list - I could do this by using a conditional loop with <cfif> tags to make sure no duplicates appear. Something like:

<CFSET oldList = &quot;1,2,3,4,5,6,7,8,9&quot;>
<CFSET newList = &quot;&quot;>
<CFLOOP Condition = &quot;ListLen(myList, &quot;,&quot;) LT ListLen(oldList, &quot;,&quot;)&quot;>
<CFSET randPos = RandRange(1,ListLen(oldList, &quot;,&quot;))>
<CFSET randVal = ListGetAt(oldList,randPos, &quot;,&quot;)>
<CFIF ListContains(newList, randVal, &quot;,&quot;) IS 0>
<CFSET newList = ListAppend(newList, randVal, &quot;,&quot;)>
</CFIF>
</CFLOOP>

This would probably do the trick but I'm concerned that it would slow down the page due to the uncertain length of the loop. I may have to go with this unless there are any more elegant ways of doing this


Neil
 
Someone answered my question in another forum - just thought I would post the answer incase anyone finds it useful:

the trick is to delete the entry from the old list on each loop:

<cfset oldlist=&quot;1,2,4,7,9,12,22,31,35&quot;>
<cfset newlist=&quot;&quot;>
<cfset temp=randomize(gettickcount())>
<cfloop from=&quot;#listlen(oldlist)#&quot; to=&quot;1&quot; step=&quot;-1&quot; index=&quot;i&quot;>
<cfset p=randrange(1,i)>
<cfset newlist=listappend(newlist,listgetat(oldlist,p))>
<cfset oldlist=listdeleteat(oldlist,p)>
</cfloop>
<cfoutput>#newlist#</cfoutput>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top