Utility Functions: ArrayRandomize()

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>

 

Comments

Jon Hartmann, July 2011

I'm Jon Hartmann and I'm a Javascript fanatic, UX/UI evangelist and former ColdFusion master. I blog about mysterious error messages, user interface design questions, and all things baffling and irksome about programming for the web.

Learn more about me.

Post a job. Find one. authenticjobs.com

Interested in becoming a sponsor? Contact me.