Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

as3 random array - randomize array - actionscript 3

How do you randomize an array using actionscript 3?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is a short version using Array.sort() function:

var arr : Array = [0,1,2,3,4,5,6,7,8,9];

function randomize ( a : *, b : * ) : int {
    return ( Math.random() > .5 ) ? 1 : -1;
}

trace( arr.sort( randomize ) );

If you don't get "enough" randomness you can sort twice :)

EDIT - explanation line by line:

For Array class method sort() you can pass not only sort options like Array.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:

A comparison function should take two arguments to compare. Given the elements A and B, the result of compareFunction can have a negative, 0, or positive value:

  • A negative return value specifies that A appears before B in the sorted sequence.
  • A return value of 0 specifies that A and B have the same sort order.
  • A positive return value specifies that A appears after B in the sorted sequence.

Note: compare function parameters might be typed (if your array is typed) and have any name you want eg.:

function compareElements ( elementA : SomeClass, elementB : SomeClass ) : int;

This method is very useful when you need to sort array elements by their special properties. In randomization case compareFunction randomly returns -1, 0 or 1 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 and 1. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...