Random text generator in as3? - actionscript-3

I want to have a dynamic text field that will generate different texts that I specify. How can I do that? I am using actionscript 3

If you want random chars try this :
function generateRandomString(strlen:Number):String{
var chars:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var num_chars:Number = chars.length - 1;
var randomChar:String = "";
for (var i:Number = 0; i < strlen; i++){
randomChar += chars.charAt(Math.floor(Math.random() * num_chars));
}
return randomChar;
}
trace(generateRandomString(7));

var array:Array = new Array ("Apples","Bananas","Grapes"); //create an array of possible strings
var randomIndex:int = Math.floor ( Math.random () * array.length ); //generate a random integer between 0 and the length of the array
myTextField.text = array [ randomIndex ]; //put the random string in your text field

Related

How To Create An Array of Movie Clip with number

I have multi movieclips in my stage and they have instanceName e.g. k1,k2,... . I want to createar=[k1,k2,k3,k4, ...].
var i: int;
var ar: Array = new Array();
for (i = 1; i < 5; i++)
{
ar[i-1] = ["k" + i];
}
trace(ar);
ar[1].x = 100;
But the end of code does not perform.
What you want to do is to create an array of MovieClips, but instead of it you create an array of Arrays of Strings. To achieve your goal, you need to find an instance of a clip on stage by its name. Here is how you can try to do that:
const array:Array = new Array();
for(var i:int = 0; i < 5; i++) {
const childName:String = "k" + (i + 1);
const myMovieClip:MovieClip = stage.getChildByName(childName) as MovieClip;
array.push(myMovieClip);
}

Simplest way to prevent math.random form selecting the same number twice (AS3)

I have a random number variable defined as below
var rannum:Number = Math.floor(Math.random()*50+1);
Then I have a trigger that calls for a new random number everytime a button is clicked
ranbtn.addEventListener(MouseEvent.CLICK, reran);
function reran (event:MouseEvent):void
{
rannum = Math.floor(Math.random()*50+1);
}
I would like to prevent the same random number from being selected until all the numbers have been selected and then possibly start over?
I found a few threads like this one but none of them were specifically what I needed
You need to create an array of the possible values and each time you retrieve a random index from the array to use one of the values, you remove it from the array.Here you have an easy example with javascript.
var uniqueRandoms = [];
var numRandoms = 50;
function makeUniqueRandom() {
// refill the array if needed
if (!uniqueRandoms.length) {
for (var i = 0; i < numRandoms; i++) {
uniqueRandoms.push(i);
}
}
var index = Math.floor(Math.random() * uniqueRandoms.length);
var val = uniqueRandoms[index];
// now remove that value from the array
uniqueRandoms.splice(index, 1);
return val;
}
I've found another option, You can declare an array of Integers:[1,2,3,4...50] and sort them randomly.
var sorted:Array = [];
for(var i:int = 0; i < 50; i++){
sorted.push(i);
}
//I'm making a copy of sorted in unsorted
var unsorted:Array = sorted.slice();
//Randomly sort
while(sorted.join() == unsorted.join()){
unsorted.sort(function (a:int, b:int):int { return Math.random() > .5 ? -1 : 1; });
}
If you get a selected num, you can add one until it is not selected.
Create a list of integers from 1 to 50.
Pick a random integer from the list and remove it.
When there are no more integers left (after 50 picks), repeat step 1.
Code:
function createRangeOfIntegers(from:int, to:int):Vector.<int> {
if (from >= to) throw new ArgumentError("Invalid arguments");
var integers:Vector.<int> = new <int>[];
for (var i:int = from; i <= to; i++) {
integers.push(i);
}
return integers;
}
function getRandomInteger(integers:Vector.<int>):int {
var index:int = Math.random() * integers.length;
var integer:int = integers.splice(index, 1)[0];
return integer;
}
Example:
// create all the possible integers
var integers:Vector.<int> = createRangeOfIntegers(1, 50);
// select a random integer
var random:int = getRandomInteger(integers);
// When you've selected all integers you can start over
if (integers.length == 0)
integers = createRangeOfIntegers(1, 50);

Showing randomly sorted array over multiple text fields

I have a randomly sorted array of, say, 3 items. Instead of displaying all 3 items in one dynamic text box (see code below), I'd like to display each item across 3 different text boxes. How might I go about doing this?
var Questions:Array = new Array;
Questions[0] = "<b><p>Where Were You Born?</p><br/>";
Questions[1] = "<b><p>What is Your Name?</p><br/>";
Questions[2] = "<b><p>When is Your Birthday?</p><br/>";
function randomize (a:*, b:*): int {
return (Math.random() > .5) ? 1: -1;
}
questions_txtbox.htmlText = Questions.toString() && Questions.join("");
The following code accomplishes what you were asking for, although the shuffling function is crude, it gets the job done. I also dynamically generated the three Text Fields as opposed to creating them on the stage and giving them unique instance names, so you will need to adjust the x/y coordinates for these new textfields as you see fit. I tested this on Flash CC 2014 and it worked properly.
import flash.text.TextField;
var Questions:Array = new Array();
Questions[0] = "<b><p>Where Were You Born?</p><br/>";
Questions[1] = "<b><p>What is Your Name?</p><br/>";
Questions[2] = "<b><p>When is Your Birthday?</p><br/>";
var shuffleAttempts:int = 10 * Questions.length;
var questionTextFields:Array = new Array(3);
function randomize (a:*, b:*): int {
return (Math.random() > .5) ? 1: -1;
}
function shuffleQuestions(arr:Array):void {
var temp:String;
for(var i:int = 0; i < shuffleAttempts; i++ ) {
var randIndex1:int = Math.floor(Math.random() * Questions.length);
var randIndex2:int = Math.floor(Math.random() * Questions.length);
if( randIndex1 != randIndex2 ) {
temp = Questions[randIndex1];
Questions[randIndex1] = Questions[randIndex2];
Questions[randIndex2] = temp;
}
}
}
shuffleQuestions(Questions); // shuffle question list
for( var questionIndex:int = 0; questionIndex < 3; questionIndex++ ) {
if( questionIndex < Questions.length ) {
var questionField = new TextField(); // create new text field
questionField.htmlText = Questions[questionIndex]; // take a question from the questions list and set the text fields text property
questionField.y = questionIndex * 20; // move the text field so that it does not overlap another text field
questionField.autoSize = "left"; // autosize the text field to ensure all the text is readable
questionTextFields[questionIndex] = questionField; // store reference to question textfield instance in array for later use.
addChild(questionField); // add textfield to stage
}
}

passing random values from one array to another without repetitions

I have an array (say 'origA') which contains 20 values and also another array (say "itemA" with only 1 value in it. I need to push any 10 random values of "origA" into "itemA". But i cannot push a same value which is already pushed into "itemA".
How can we do this?
You can create a copy of origA and remove from it the items you add to itemA:
Non optimized version:
var origA:Array = [1, 2, 3, 4, 5, 6, 7];
var itemA:Array = [0];
var copyA:Array = origA.concat();
var N:int = 10;
var n:int = Math.min(N, copyA.length);
for (var i:int = 0; i < n; i++) {
// Get random value
var index:int = Math.floor(Math.random() * copyA.length);
var value:int = copyA[index];
// Remove the selected value from copyA
copyA.splice(index, 1);
// Add the selected value to itemA
itemA.push(value);
}
trace(itemA);
//0,1,7,2,6,4,3,5
Optimized version (no calls to length, indexOf, splice or push inside the loop):
var origA:Array = [1, 2, 3, 4, 5, 6, 7];
var itemA:Array = [0];
var copyA:Array = origA.concat();
var copyALength:int = copyA.length;
var itemALength:int = itemA.length;
var N:int = 10;
var n:int = Math.min(N, copyALength);
for (var i:int = 0; i < n; i++) {
// Get random value
var index:int = Math.floor(Math.random() * copyALength);
var value:int = copyA[index];
// Remove the selected value from copyA
copyA[index] = copyA[--copyALength];
// Add the selected value to itemA
itemA[itemALength++] = value;
}
trace(itemA);
//0,2,5,7,4,1,3,6
Edit1: If your original array has only a few items, use my first version or any other solution in the other answers. But if it may have thousands items or more, then I recommend you use my optimized version.
Edit:2 Here is the time taken to copy 1,000 randomly chosen items from an array containing 1,000,000 items:
All other versions: 2000ms
Optimized version: 12ms
Optimized version without cloning the original array: 1ms
// Define how many random numbers are required.
const REQUIRED:int = 10;
// Loop until either the original array runs out of numbers,
// or the destination array reaches the required length.
while(origA.length > 0 && itemA.length < REQUIRED)
{
// Decide on a random index and pull the value from there.
var i:int = Math.random() * origA.length;
var r:Number = origA[i];
// Add the value to the destination array if it does not exist yet.
if(itemA.indexOf(r) == -1)
{
itemA.push(r);
}
// Remove the value we looked at this iteration.
origA.splice(i, 1);
}
Here's a real short one. Remove random items from the original array until you reach MAX, then concat to the target Array:
const MAX:int = 10;
var orig:Array = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var target:Array = [];
var tmp:Array = [];
var i : int = -1;
var len : int = orig.length;
while (++i < MAX && len > 0) {
var index:int = int( Math.random()*len );
tmp[i] = orig[index];
orig[index] = orig[--len];
}
target = target.concat(tmp);
EDIT
Adopted #sch's way of removing items. It's his answer that should be accepted. I just kept this one for the while-loop.

Read set of numbers from txt file

I've been working on a project for a while but got stuck where I have a text file that contains a set of numbers in this format:
1-2-3-4
1-2-3-4
1-2-3-4
1-2-3-4
So I must read the numbers from the file and put them in an array according to the column so at the end I have
column1:Array (1,1,1,1)
column2:Array (2,2,2,2)
..... and so on. I can't figure how to do this.
What I managed to do was read all the file and have all the numbers in 1 array but just that.
Here's the code
var myTextLoader:URLLoader = new URLLoader;
var txtArray:Array;
myTextLoader.load(new URLRequest(inputFile.text));
myTextLoader.addEventListener(Event.COMPLETE,onLoaded);
function onLoaded(e:Event):void
{
txtArray = e.target.data.split(/\-|\n/g);
}
before split \n \r to array (reading with a loop)
and the same with... -
a loop in loop to get a multidimensional array
in mind the result is a "table"
finally to get a result do this.
variable[file][column]
a[2][3] ----> 4
;)
Try splitting it into two parts, first by line, then by element:
function onLoaded(e:Event):void
{
preArray:Array = e.target.data.split(/\n/g);
txtArray = new Array();
for(var i:int = 0; i < preArray.length; i++) {
txtArray.push(preArray[i].split(/\-/g));
}
}
This will give you a 2D array, which you'd access like this:
textArray[0][0]; // result: 1
textArray[2][3];
Et cetera.
Thanks to Llanis who gave me the idea. This is my final code. Sorry i didn't tag the language it never ocurred to me i'm new.
myTextLoader.load(new URLRequest(inputWX.text));
myTextLoader.addEventListener(Event.COMPLETE,onLoaded);
function onLoaded(e:Event):void
{
txtArray = e.target.data.split(/\-|\n/g);
var wArray:Array = new Array(txtArray.length/4);
var xArray:Array = new Array(txtArray.length/4);
var yArray:Array = new Array(txtArray.length/4);
var zArray:Array = new Array(txtArray.length/4);
var a:int = 0;
var b:int = 0;
var c:int = 0;
var d:int = 0;
var columna:int = 1;
for(var arrayIndex:int = 0; arrayIndex <= txtArray.length-1;arrayIndex++)
{
switch(columna){
case 1: wArray[a] = txtArray[arrayIndex]; a+=1;
break;
case 2: xArray[b] = txtArray[arrayIndex]; b+=1;
break;
case 3: yArray[c] = txtArray[arrayIndex]; c+=1;
break;
case 4: zArray[d] = txtArray[arrayIndex]; d+=1;
break;
}
if(columna == 4)
columna = 1;
else columna++;
}
}