0

I have recently worked on AS3 project with a module that works like this:

I have 50 strings and I am picking one randomly of them at a given time. When I am done with the picked one I choose another one of the 49 left again randomly and so on.

I managed to solve this problem using helper arrays, for cycles, mapping index numbers with the strings. Although every thing works just fine I found my code very messed and hard to understand.

Is there a much more easy and cleaner way to solve this problem in AS3?

Maybe there is a library for getting random string out of strings?

4

2 回答 2

3

像这个类这样简单的东西:

public class StringList
{

    private var _items:Array = [];

    public function StringList(items:Array)
    {
        _items = items.slice();
    }

    public function get random():String
    {
        var index:int = Math.random() * _items.length;
        return _items.splice(index, 1);
    }

    public function get remaining():int{ return _items.length; }

}

及其用法:

var list:StringList = new StringList(['a', 'b', 'c', 'd']);

while(list.remaining > 0)
{
    trace(list.random);
}
于 2013-07-24T10:38:00.740 回答
1

我不确定你想用这个程序做什么,但这里有一个建议:

var stringArray:Array = new Array("string1", "string2", "string2"); //your array with strings
var xlen:uint = stringArray.length-1; //we get number of iterations
for (var x:int = xlen; x >= 0; x--){ //we iterate backwards
var randomKey:Number = Math.floor(Math.random()*stringArray.length); //gives you whole numbers from 0 to (number of items in array - 1)
stringArray.splice(randomKey,1); //remove item from array with randomKey index key
 var str:String = stringArray[randomKey]; //output item into new  string variable or do whatever  
}
于 2013-07-24T10:32:47.070 回答