How do you randomize an array using actionscript 3?
相关问题
- How to get the maximum of more than 2 numbers in V
- Faster loop: foreach vs some (performance of jsper
- Convert Array to custom object list c#
- pick a random item from a javascript array
- Newtonsoft DeserializeXNode expands internal array
相关文章
- Numpy matrix of coordinates
- why 48 bit seed in util Random class?
- PHP: Can an array have an array as a key in a key-
- Accessing an array element when returning from a f
- How can I convert a PHP function's parameter l
- How to make a custom list deserializer in Gson?
- Recursively replace keys in an array
- React Native - Dynamic Image Source
If you need your array to be shuffled (your elements can not repeat). You could use this function:
Usage:
choose random string from array
usage:
I found this very helpful. I hope it can help you too.
this is how I randomize my array of 36 cards for a memory game
I had an alternative requirement where i wanted to randomly insert lots of source arrays into a target array randomly. Like Rytis i'm a big fan of the forEach, map and sort functions on Arrays.
There is a short version using Array.sort() function:
If you don't get "enough" randomness you can sort twice :)
EDIT - explanation line by line:
For
Array
class methodsort()
you can pass not only sort options likeArray.CASEINSENSITIVE, Array.DESCENDING
and so on but also your own custom compare function reference (a callback) that accepts two parameters (two elements from array to compare). From AS3 documentation:Note: compare function parameters might be typed (if your array is typed) and have any name you want eg.:
This method is very useful when you need to sort array elements by their special properties. In randomization case
compareFunction
randomly returns-1, 0
or1
and makes array elements to switch their places (indices). I have found that better randomization (in my subjective and mathematically untested opinion) is when method returns only-1
and1
. Also have in mind that sorting function with custom compare function doesn't compare elements sequentially so in some special cases randomization results may differ from what you might expect.