zshuffle

A very simple function to shuffle an array.

function zshuffle {
	RANDOM=$$

	local count array shuffled size index
	integer count size index
	typeset -a array shuffled

	array=($*) # Limited to 32767 elements because $RANDOM
	
	size=${(w)#array}
	((size > 32767)) && {
		print "Ops! too many big array"
		return 1
	}
	
	while ((count++ < size))
	do
		index=$((1 + (${(w)#array} * RANDOM / 32767)))
		shuffled+=($array[$index])
		array[$index]=()
	done
	
	[ -n "$shuffled[*]" ] && print "$shuffled[*]" || return 1
}
 
code/scripts/start.txt · Last modified: 2010/01/05 09:20 (external edit)