AS3 - Preventing duplicates from being selected from an array
本问题已经有最佳答案,请猛点这里访问。
我有一个要以随机顺序放置在舞台上(使用TextFields)的八个字符串组成的数组。
我可以毫无问题地选择任意8个字符串,使用Math.random选取一个介于0到7之间的数字,然后将该项目放在该索引处的舞台上。
但是我正在努力防止添加重复项。有没有人有什么建议?
谢谢
随机排列数组,然后循环遍历。一些很好的例子可以在这里找到:
http://bost.ocks.org/mike/shuffle/
这是您可以执行的一种方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var strings:Array = ["one","two","three","four","five","six"]; // create a clone of your array that represents available strings var available:Array = strings.slice(); // choose/splice a random element from available until there are none remaining while (available.length > 0) { var choiceIndex:int = Math.random() * available.length; var choice:String = available[choiceIndex]; available.splice(choiceIndex,1); trace (choice); // you could create a textfield here and assign choice to it // then add it to the display list } |
概念是创建一个数组的克隆,然后从该数组中随机获取1个元素,直到没有剩余的元素为止。这样可以确保您永远不会重复。
每次运行math.random函数时,都会使用splice从数组中删除结果索引处的字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var source:Array = ["one","two","three","four","five","six","seven","eight"]; var displayedIndices:Array = []; var index:uint = Math.floor(Math.random())*source.length; displayedIndices.push(index); var newString:String = source[index]; addChildAt(myTextField(newString), index); //I suppose myTextField creates a textfield and returns it //now you want to be sure not to add the same string again //so you take a random index until it hasn't already been used while (displayedIndices.indexOf(index) != -1) { index = Math.floor(Math.random())*source.length; } //there your index has not already been treated displayedIndices.push(index); var newString:String = source[index]; addChildAt(myTextField(newString), index); |
此代码非常具有教育意义,您只应使用它的第二部分。