如何在不循环的情况下获取数组

时间:2014-05-19 06:16:36

标签: actionscript-3 actionscript

我想创建一个数字数组,然后将这些数字随机化。

1 个答案:

答案 0 :(得分:0)

这是我提出的。它做了两件事。

  1. 它获取一个从0到指定长度的数组。主要问题是什么。
  2. 然后随机化该数组中的项目

    // returns [1,2,3,4,5,6,7,8,9,10] except shuffled
    var array:Array = getSequenceArray(10);
    
    
    /**
     * Get an array of the range of numbers from 1 to the number specified and randomize them.
     * */
    public function getRandomArray(count:int):Array {
        // this part is not looped. yay!
        var array:Array = new Array(count).map(function (item, index) { return index + 1; });
    
        return randomizeArray(array);;
    }
    
    /**
     * Randomize items in an array
     * */
    public function randomizeArray(original:Array, cloneArray:Boolean = true):Array {
        var length:int = original.length;
        var shuffledArray:Array = [];
        var newArray:Array = original.slice();
        var randomNumber:Number;
    
        // this is still using a loop. this loop is less of an issue than the first
        while (length) {
            randomNumber = Math.floor(Math.random() * length);
            shuffledArray.push(newArray.splice(randomNumber, 1)[0]);
            length--;
        }
    
        if (!cloneArray) {
            original.splice(0, shuffledArray.length); 
            original.push.apply(this, shuffledArray);
            return original;
        }
    
        return shuffledArray;
    
    }