0

I've got an array of eight strings that I want to place on the stage (using TextFields) in a random order.

I can select any 8 of the strings without a problem, using Math.random to pick a number between 0-7 and placing the item at that index onto the stage.

But I'm struggling to prevent duplicates from being added. Does anyone have any suggestions?

Thank you

kevio17
  • 3
  • 2

4 Answers4

1

Shuffle the array, then loop through it. Some great examples can be found here:

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

Bart
  • 547
  • 2
  • 12
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);

This code is quite educationnal, you should only use the second part of it.

Kodiak
  • 5,978
  • 17
  • 35
  • Thanks. I tried something similar to start with - using a second array to store the strings that had already been added, then generating a new random number if the next string was already contained in that array. – kevio17 May 02 '13 at 12:47
0

Every time you run the math.random function remove the string at the resulting index from the array using splice.

0

This is one way you could do it :

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
}

The concept is that you create a clone of the array and then randomly take 1 element from that array, until you have none left. That ensures that you never have a duplicate.

prototypical
  • 6,731
  • 3
  • 24
  • 34