CFLib.org – Common Function Library Project

ArrayShuffle(ar)

Last updated October 9, 2001

author

Ivan Latunov

Version: 1 | Requires: CF5 | Library: DataManipulationLib

Description:
Shuffles the values in a one-dimensional array. This functions takes a one-dimensional array and returns a new one with the values from the first randomly shuffled.

Return Values:
Returns an array.

Example:

<cfset a=arrayNew(1)>
<cfloop index="i" from="1" to="10">
	<cfset a[i]=i>
</cfloop>
<cfset a1=ArrayShuffle(a)><br><br>

<CFLOOP FROM="1" TO="#ArrayLen(a1)#" INDEX="i">
<CFOUTPUT>
#a1[i]#<BR>
</CFOUTPUT>
</CFLOOP>

Parameters:

Name Description Required
ar One dimensional array you want shuffled. Yes

Full UDF Source:

/**
 * Shuffles the values in a one-dimensional array.
 * 
 * @param ar 	 One dimensional array you want shuffled. 
 * @return Returns an array. 
 * @author Ivan Latunov (ivan@cfchat.net) 
 * @version 1, October 9, 2001 
 */
function ArrayShuffle(ar) {
	var ar1=ArrayNew(1);
	var i=1;
	var n=1;
	var len=ArrayLen(ar);
	if (NOT IsArray(ar,1)) {
		writeoutput("Error in <Code>ArrayShuffle()</code>! Correct usage: ArrayShuffle(<I>Array</I>) - Shuffles the values in one dimensional Array");
		return 0;
	}
	
	if (ArrayLen(ar) eq 0) {
		return ar1;
	}
	
	for (i=1; i lte len; i=i+1) {
		n = RandRange(1,ArrayLen(ar));
		ArrayAppend(ar1,ar[n]);
		ArrayDeleteAt(ar,n);
	}
	return ar1;
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson