Utility Functions: ArrayRandomize()
- November 2, 2008 4:30 AM
- ColdFusion, Utility Function
- Comments (0)
A simple array randomization option. Note that although I use "CFMX_COMPAT" as the default randomization algorithm, you should probably always use "SHA1PRNG" to get better results.
<cffunction name="ArrayRandomize" access="public" output="true" returntype="array">
<cfargument name="array" type="array" required="true" />
<cfargument name="algorithm" type="string" required="false" default="CFMX_COMPAT" />
<!---
Fisher-Yates shuffle
http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
--->
<cfset var i = ArrayLen(arguments.array) />
<cfset var k = 0 />
<cfset var temp = "" />
<cfif i gt 0>
<cfloop condition="i gt 0">
<cfset k = RandRange(1, i, arguments.algorithm) />
<cfset temp = arguments.array[i] />
<cfset arguments.array[i] = arguments.array[k] />
<cfset arguments.array[k] = temp />
<cfset i = i - 1 />
</cfloop>
</cfif>
<cfreturn arguments.array />
</cffunction>
<cfargument name="array" type="array" required="true" />
<cfargument name="algorithm" type="string" required="false" default="CFMX_COMPAT" />
<!---
Fisher-Yates shuffle
http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
--->
<cfset var i = ArrayLen(arguments.array) />
<cfset var k = 0 />
<cfset var temp = "" />
<cfif i gt 0>
<cfloop condition="i gt 0">
<cfset k = RandRange(1, i, arguments.algorithm) />
<cfset temp = arguments.array[i] />
<cfset arguments.array[i] = arguments.array[k] />
<cfset arguments.array[k] = temp />
<cfset i = i - 1 />
</cfloop>
</cfif>
<cfreturn arguments.array />
</cffunction>