AS3随机序列 - 随机阵列 - 动作3阵列、序列、动作

2023-09-09 21:32:39 作者:磕磕绊绊从不言分离

如何使用ActionScript 3,你随机阵列?

How do you randomize an array using actionscript 3?

推荐答案

目前使用中的Array.sort()函数的一个短版:

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 :)

编辑 - 一行解释行:

有关阵列类方法的sort()您可以通过不喜欢只排序选项Array.CASEINSENSITIVE,Array.DESCENDING 等,而且自己的自定义比较函数的引用(回调)接受两个参数(从数组的两个元素进行比较)。从AS3文档:

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和B,compareFunction的结果可以具有负的,0或正的值:

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:   在负的返回值指定一个出现在B的排序顺序之前。   的返回值为0指定A和B具有相同的排序顺序。   正收益值指定一个出现在B在排序序列之后。    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;

当你需要用他们特殊的数组元素进行排序这种方法是非常有用的。在随机的情况下的compareFunction 随机返回 -1,0 1 并使得数组元素来切换他们的位置(指数)。我发现,更好的随机化(在我的主观和数学未经测试的意见)是当方法只返回 1 1 。也有记住,使用自定义的排序功能比较功能不比较的元素依次所以在某些特殊情况下,随机的结果可能不同于你所期望的东西。

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.