0

我有一个包含八个字符串的数组,我想以随机顺序放置在舞台上(使用 TextFields)。

我可以毫无问题地选择任意 8 个字符串,使用 Math.random 选择 0-7 之间的数字并将该索引处的项目放到舞台上。

但我正在努力防止添加重复项。有没有人有什么建议?

谢谢

4

4 回答 4

1

随机播放数组,然后循环遍历它。一些很好的例子可以在这里找到:

http://bost.ocks.org/mike/shuffle/

于 2013-05-02T12:43:36.463 回答
0
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);

这段代码很有教育意义,你应该只使用它的第二部分。

于 2013-05-02T12:40:03.133 回答
0

这是您可以做到的一种方法:

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 个元素,直到没有剩余元素为止。这样可以确保您永远不会有重复。

于 2013-05-02T16:41:38.813 回答
0

每次运行 math.random 函数时,使用 splice 从数组中删除结果索引处的字符串。

于 2013-05-02T13:06:22.197 回答