I have 2 multi-dimensional arrays that I'm trying to compare data against. While the length of the nested arrays may vary on a case-by-case basis, for each instance the lengths will be the same and mirrored between both arrays AND the first array[0] of each will contain the exact same info. The only thing that will/may vary is the order the headers may appear in array[0]. It may be
h1, h2, Id
in the first and
Id, h1, h2
in the second array.
Full Example
1st array
[ [ Header1 , Header2 , ID ] , [ dataA , dataB , 000 ] ]
2nd array
[ [ Header1 , Header2 , ID ] , [ dataA , dataB , 111 ] ]
Question
How can I parse, loop, split, whatever (still new to this) so that I can compare each values and put them all into a single array?
Result Wanted
[ [ oldHeader1 , oldHeader2 , oldID , newHeader1 , newHeader2 , newID ] , [ dataA , dataB , 000 , dataA , dataB , 111 ] ]
and yes, dataA and dataB should be the same from both sources. That is what I'm comparing against, the IDs of each are the only things that should be different. If dataA doesn't match but dataB does, I'd like to continue but add a logging. But that's a later step.
I've thought about looping through 1st array and taking each value, then looping through the 2nd value to see if that value exists. That would be all well and good but I can't seem to figure out how to .push that value and keep everything in order. These values are also being pulled from a sheet but I read that it is faster to generate an array and use Google's server to do the work rather than look at each cell, vlookup or find, return a result, ++ and iterate.
Any advice here would be great, thanks!
Here is the code I'm using to generate the 2 arrays I'm going to compare as an FYI. Maybe there's something here that I can modify? I call this function twice, with a file that contains source info and a file that contains destination info.
//This will take a sheet and an array of headers and return the subset in a new array
function grabColumnByHeader(headers,sheet,whichID) {
var initialArray = new Array(); //Array to store sheet data
var headerIndex = new Array(); //Blank array to house header index(es)
var outputArray = []; //Will be returned
var data = sheet.getDataRange(); //all data
var dataNumRows = data.getNumRows(); //number of rows
var dataNumCol = data.getNumColumns(); //number of columns
initialArray = sheet.getRange(1, 1, dataNumRows, dataNumCol).getValues();
//Get the index(es) of header(s). This is assuming that headers are in row 1
for (i = 0;i<1;++i){
for (j = 0;j<dataNumCol;++j){
//loop through headers var for each header
for (k = 0;k<headers.length;++k){
if(initialArray[i][j].toString().toUpperCase() == headers[k][i].toString().toUpperCase()) {
headerIndex.push(j);
}
}
}
}
//Using the array's indexes from headerIndex, loop through and grab values
//If coming from SOURCE file, prepend 'SOURCE_'
for (i = 0;i<dataNumRows;++i) {
outputArray[i] = [];
for (j = 0;j<headerIndex.length;++j) {
if (i == 0 && whichID == 'TRUE') {
outputArray[i][j] = 'SOURCE_' + initialArray[i][headerIndex[j]];
} else {
outputArray[i][j] = initialArray[i][headerIndex[j]];
}
}
}
//Logger.log(outputArray);
return outputArray;
}
Update
Here is the code I've been able to google fu together and use my basic knowledge. I realize that it is performing unnecessary loops and this is still a work in progress:
var tempArray = [];
var idIndex;
//get index of ID so it can be skipped in comparison
for (i=0;i<1;++i) {
for (j=0;j<newData[i].length;++j) {
if (newData[i][j].toString().toUpperCase() == 'ID') {
idIndex = j;
}
}
}
//Logger.log(idIndex);
for (i=0;i<newData.length;++i) {
tempArray[i] = [];
//if on headers, automatically concatenate and add to tempArray
if (i==0) {
tempArray[i] = newData[i].concat(oldData[i]);
}
else {
//Logger.log('newData['+i+']');
for (j=0;j<newData[i].length;++j) {
//for newData[i][j], begin looking in oldData
//if we're not comparing indexes then
if (j != idIndex) {
//Logger.log('newData['+i+']['+j+']');
//begin looping through the oldData arrays
for (k=0;k<oldData.length;++k){
//Logger.log('newData['+i+']['+j+'] == oldData['+k+']['+j+']');
if (newData[i][j] == oldData[k][j]) {
//NEED TO MAKE SURE HERE THAT ++j IS THE SAME TOO
tempArray[i] = newData[i].concat(oldData[k]);//continue on with j
break;
}
}
}
//continue through for(j)
}
}
//continue through for(i)
}
output.getRange(1, 1, tempArray.length, tempArray[0].length).setValues(tempArray);
Found my own answer after enough trial and error. May not be the way a pro would do it, but works for me:
var tempArray = []; //will be used for output
var sameArray = []; //will look like this [sameIndex,sameCount]
var sameIndex = ''; //will get the index number of match to be used when pushing to tempArray
var sameCount = 0; //if count is == my keys-ID then push to tempArray
//concat the headers, as this will be a constant
tempArray[0] = newData[0].concat(oldData[0]);
for (i=1;i<newData.length;++i) {
//reset variables after each [i]
//these are used to verify if my newData array and oldData array are the same
sameArray = [];
sameIndex = '';
sameCount = 0;
for (j=0;j<newData[i].length;++j) {
//for newData[i][j], begin looking in oldData
//we're not comparing our IDs because we know they'll be different
//pulled those out earlier and set to idIndex
if (j != idIndex) {
//begin looping through the oldData arrays
for (k=1;k<oldData.length;++k){
for (l=0;l<oldData[k].length;++l) {
if (l != idIndex) {
if (newData[i][j] == oldData[k][l]){
sameArray[0] = k;
sameArray[1] = ++sameCount;
}
}
}
}
}
//since looped through all of oldData array, check to see
//if the amount of matches in a single row were keyCount-1
//keyCount is my variables and we subtract 1 because not comaring IDs
if (sameArray[1] == keyCount-1) {
tempArray.push(newData[i].concat(oldData[sameArray[0]]));
} else {
//Will be used to catch indexes that didn't match
}
}
}
output.getRange(1, 1, tempArray.length, tempArray[0].length).setValues(tempArray);
Related
So i'm having trouble trying to build out an excel sheet faster than 20 seconds. I'm using the below to compare 3 different arrays to then print out the answer i need.
for (let i = 0; i < this.arrayNumberOne[0].length; i++) {
let orangeOne = this.arrayNumberOne[0][i]['item_1'];
let orangeTwo = this.arrayNumberOne[0][i]['item_2'];
let orangeThree = orangeOne.concat(orangeTwo)
for (let k = 0; k < this.arrayNumberTwo[0].length; k++) {
let appleOne = this.arrayNumberTwo[0][k]['item_1'];
for (let j = 0; j < this.arrayNumberThree[0].length; j++) {
let grapeOne = this.arrayNumberThree[0][j]['item_1'];
let grapeTwo = this.arrayNumberThree[0][j]['item_2'];
let grapeThree = this.arrayNumberThree[0][j]['item_3'];
if (orangeThree == grapeOne && appleOne == grapeTwo) {
if (grapeThree == null || grapeThree == '') {
// print to response to excel
}
else if (grapeThree == 'sells') {
// print stuff to excel
}
else if (grapeThree == 'buys') {
// print stuff to excel
}
}
}
}
}
I was looking at hashmaps and interfaces, but im not quite sure how i could apply that here. I would appreciate any alternatives to making the above faster.
Edit:
Playground Link
What sets off a red flag here is that you have 3 nested loops, but your data is 2D, so you would expect at most 2 nested loops (one for X and one for Y). What you want to focus on is that the process for getting the value of each cell should be as fast as possible, since that is what needs to happens to largest number of times.
The key here is pre-process your values (what goes in the cells of your spreadsheet, buy/sell/blank) in a way that makes it very quick look those up.
For example:
// Index all actions by player id and item name
const indexedActions: {
[playerId: string]: {
[itemCatName: string]: string
}
} = {}
// Loop through all actions once to index them.
for (const {playerId, itemCatName, action} of actions) {
if (!indexedActions[playerId]) indexedActions[playerId] = {}
indexedActions[playerId][itemCatName] = action
}
After that runs you'll have data like:
{
"12": {
"potionsmall-potion": 'buy'
// etc...
}
// etc...
}
That's important because now looking up any cell is as easy as:
indexedActions[playerId][itemName]
Which lets you completely remove that most inner loop.
// Loop through items
for (let i = 0; i < items.length; i++) {
let itemCat = items[i]['itemCategory']
let itemNam = items[i]['itemName']
let combineCat = itemCat.concat(itemNam)
// Loop through players
for (let k = 0; k < players.length; k++) {
let playerIdentify = players[k]['playerId']
// Lookup what this player did with this item
const actionToDo = indexedActions[playerIdentify][combineCat]
// do stuff with action
}
}
Before Optimization
for every item
for every player
for every action
doLogic()
Here "doLogic" is executed itemCount * playerCount * actionCount times.
After Optimization
for every action
index each action
for every item
for every player
doLogic()
Now we do a little more work up front, but doLogic is only executed itemCount * playerCount times, which is a huge improvement.
And as a bonus it's less code and easier to read!
See playground
Here's what I'm trying to do. I'm making a game where opponents guess each other's word, and each guess has direct and indirect hits. See asterisks for where I'm having an issue.
var directSum = 0
var indirectSum = 0
var words = ["canon", "cnams"]
var secretWord = Array(words[0].characters)
var guessWord = Array(words[1].characters)
var secretWordInd = [Character]()
var guessWordInd = [Character]()
let dir1 = secretWord[0] == guessWord[0]
let dir2 = secretWord[1] == guessWord[1]
let dir3 = secretWord[2] == guessWord[2]
let dir4 = secretWord[3] == guessWord[3]
let dir5 = secretWord[4] == guessWord[4]
if dir1 && dir2 && dir3 && dir4 && dir5 {
print ("you won!")
}
if dir1 {
directSum += 1
} else {
secretWordInd.append(secretWord[0])
guessWordInd.append(guessWord[0])
}
if dir2 {
directSum += 1
} else {
secretWordInd.append(secretWord[1])
guessWordInd.append(guessWord[1])
}
if dir3 {
directSum += 1
} else {
secretWordInd.append(secretWord[2])
guessWordInd.append(guessWord[2])
}
if dir4 {
directSum += 1
} else {
secretWordInd.append(secretWord[3])
guessWordInd.append(guessWord[3])
}
if dir5 {
directSum += 1
} else {
secretWordInd.append(secretWord[4])
guessWordInd.append(guessWord[4])
**}
for var secretLetter in secretWordInd {
for var guessLetter in guessWordInd{
if secretLetter == guessLetter {
secretWordInd.remove(at:secretWordInd.indexOf(secretLetter))
guessWordInd.remove(at:guessWordInd.indexOf(guessLetter))
indirectSum += 1
}
}
}**
var score = [directSum, indirectSum]
what I need to do is count every time there's a character in Array:SecretWordInd that matches a character in Array:guessWordInd, remove only those two characters(one from each string), and indirectSum += 1 for every time this occurs. If there are 2 "a"s in one and 1 in the other, for instance, the function needs to remove 1 a from each. That means the output of the function for directSum, indirectSum in this case should be [1,2] since there is only one indirect hit from one "n" from the guess word. This is what is making the function complicated for me. The number of values in both arrays will not be constant. I can't figure out how to use a method to do this(.contains is for only strings I think). Your help is greatly appreciated! Thanks!
You should look into Array, Set and String data types in the documentation, they provide lots of functions to perform that kind of calculations and transformations.
For example:
var secretWord = "canon"
var guessWord = "cnams"
// identify shared letters using sets
let sharedLetters = Set(secretWord.characters).intersection(Set(guessWord.characters))
// count number of shared letters present in both words
let sharedCounts = sharedLetters.map{ c in (c, secretWord.characters, guessWord.characters) }
.map{ (c,s,g) in (c, s.filter{$0==c}, g.filter{$0==c}) }
.map{ (c,s,g) in (c, min(s.count,g.count)) }
// count same letters at same position and shared
// (if you're making a mastermind game, you should subtract directCount from indirectCount)
let directCount = zip(secretWord.characters,guessWord.characters).filter{$0==$1}.count
let indirectCount = sharedCounts.map{$0.1}.reduce(0,+)
// remove shared letters (for count) from both strings
sharedCounts.flatMap{ Array(repeating:$0, count:$1) }
.forEach{ secretWord.remove(at:secretWord.characters.index(of:$0)!) }
sharedCounts.flatMap{ Array(repeating:$0, count:$1) }
.forEach{ guessWord.remove(at:guessWord.characters.index(of:$0)!) }
sharedLetters // {"n", "a", "c"}
sharedCounts // ("n", 1), ("a",1), ("c", 1)]
directCount // 1
indirectCount // 3
secretWord // "on"
guessWord // "ms"
As others have said this isn't the place for homework ;)
But here are some pointers as to what might be useful:
indexOf : returns index of element you are looking for, nil if not in set
remove : remove from an array
I am developing a game that has a winning combination array:
var allwinning = [
['000','010','020'],
['000','100','200'],
['000','001','002'],
['000','101','202'],
['000','011','022'],
['000','110','220']];
The player will need to pick more than 3 numbers randomly. If all numbers are within any of the combinations in allwinning, the player wins.
For example, if the player picks '111','110','000','220', the player will win because allwinning[5] has the combination['000','110','220'].
My question is, what is the best way to do this winning loop? I cannot figure out the optimum way to do this.
Currently, I have a playerpick array to keep what player had picked and possiblewin array:
var playerpick = new Array(['111','110','000','220']);
var playerpicksingle = playerpick[0];
var possiblewin = new Array([]);
Then I go through a loop to capture out the possible win combination first:
for(var i=0 ; i < allwinning.length - 1 ; i++)
{
for(var j=0 ; j <3 ; j++)
{
if(allwinning[i][j]==playerpicksingle)
{
possiblewin.Push(allwinning[i]);
}
}
}
Then I am stuck at this point. I really don't know what else to do.
I can think of two ways. One requires you to change your data structure and the other doesn't.
Without changes:
Sort the user input:
pickedNumbers.sort();
and start comparing. By sorting the values beforehand you know when you can back out and continue with the next set of numbers, i.e. you can back out early and don't have to compare all the values (in the average case).
function wins(picked, winning) {
var winningSet = [];
for (var i = 0; i < winning.length && winningSet.length < 3; i++) {
var set = winning[i];
winningSet = [];
var j = 0;
var k = 0;
while (j < set.length && k < picked.length && winningSet.length < 3) {
if (picked[k] === set[j]) {
winningSet.push(set[j]);
j++; // advance to next element in winning set
} else if (picked[k] > set[j]) {
// continue with the next set
break;
}
// maybe the next element in players picks will match
k++;
}
}
return winningSet.length === 3 ? winningSet : false;
}
The worst case scenario of this solution is O(n*m*l), but since the input is sorted, the average case will be better.
DEMO
With Array#some and Array#every the code becomes much more concise, though it looses the advantage of using sorted input. If your arrays are small it won't make a difference though:
function wins(picked, winning) {
return winning.some(function(set) {
return set.every(function(val) {
return picked.indexOf(val) !== -1;
});
});
}
It also won't give you the actual numbers that matched. The runtime is the same.
The second way would be to build some kind of trie instead of using an array of arrays:
var allwinning = {
'000': {
'010': {
'020': true
},
'100': {
'200': true
},
// ...
}
};
The structure should also be sorted, i.e. the keys of a level are all smaller then the keys of its sublevel etc.
Sort the user input as well and iterate over it. Whenever you found a matching key, you go one level deeper until you have three matches:
function wins(picked, winning) {
var winningSet = [];
for (var i = 0; i < picked.length && winningSet.length < 3; i++) {
if (picked[i] in winning) {
winningSet.push(picked[i]);
winning = winning[picked[i]];
}
}
return winningSet.length === 3 ? winningSet : false;
}
This solution has the worst case scenario of O(n), where n is the number of values the user picked (not taking into account the time it takes to test whether an object contains a specific property name. Often this is assumed to constant).
DEMO
I have two arrays, namely combo and truecombo. The user fills the combo with MovieClips by clicking on various buttons on the stage, truecombo is the correct combination.
At any given point (enterFrame) Flash is checking whether the two are the same, if yes, then do some stuff. For the time being this is my code (altered several times, like with Typecasting the indices, adding .parent at the end of combo[o] etc. 2 things will happen, either one or the other.
Either the statement will not be satisfied, at which point the adding and chopping of the combo array will continue, or the condition will be instantly met when combo.length = 6. Check my code.
UPDATE: I have a dropbox file with my current code. Click this for FLA link and here is the SWF link stripped down as always for ease and security.
/*stage.*/addEventListener(Event.ENTER_FRAME, checkthis);
function checkthis(e:Event)
{
for(var o:int=0;o<= combo.length; o++)
{
if((combo[o] == truecombo[o]) && (combo.length==truecombo.length))
{
equal=true;
}
}
if (equal==true)
{
stage.removeEventListener(Event.ENTER_FRAME, checkthis);
endSeq();
}
}
function endSeq():void
{
bravo.play();
for (var i:int = 0; i < combo.length; i++)
{
var element:DisplayObject = combo[i];
element.parent.removeChild(element);
}
firebb.gotoAndPlay(2);
windbb.gotoAndPlay(2);
spiritbb.gotoAndPlay(2);
earthbb.gotoAndPlay(2);
}
This is how I push my new elements to the combo array.
function add(element:DisplayObject)
{
twist.gotoAndPlay(2);
element.width = WIDTH;
element.height = HEIGHT;
if (this.combo.length >= MAX_ELEMENTS)
{
removeChild(this.combo.shift());
}
this.combo.push(element as DisplayObject);
this.addChild(element);
this.reorder();
}
function reorder()
{
for (var i:int = 0; i < combo.length; i++)
{
var element:DisplayObject = combo[i];
element.x = OFFSET_X + (i * SEP_X);
element.y = OFFSET_Y;
}
}
And this is how I have my truecombo and its contents created.
var fireb:firebtn = new firebtn();
var spiritb:spiritbtn = new spiritbtn();
var earthb:earthbtn = new earthbtn();
var windb:windbtn = new windbtn();
var combo:Array=new Array();
const truecombo:Array = [fireb,windb,spiritb,windb,earthb,fireb];
Sorry for the lack of comments, I'd guess it's pretty self-explanatory. Thanks in advance.
I believe combo[o] & truecombo[o] are two instances of the same class & you want them to be matched. If that is the case you may consider :
getQualifiedClassName(combo[o]) == getQualifiedClassName(truecombo[o])
To match the way you did, you must ensure the objects lying inside truecombo be referring to the same ones on stage & not new instances.
EDIT:
It seems you do not break the loop when the match is a success. Use this instead :
function checkthis(e:Event)
{
for(var o:int=0;o<= combo.length; o++)
if((combo[o] == truecombo[o]) && (combo.length==truecombo.length)) {
equal=true;
break;
}
if (equal) {
stage.removeEventListener(Event.ENTER_FRAME, checkthis);
endSeq();
}
}
Here's a really simple loop:
var equal:Boolean=true
if(combo.length == truecombo.length) {
for(var i:int=0; i<combo.length; i++) {
if(combo[i] != truecombo[i]) {
equal=false;
break;
}
}
} else {
equal=false;
}
if(equal) {
//do whatever
}
This assumes both are equal, until we find out otherwise. So if the lengths are different, they are not equal. If the ith element is different, they are not equal.
In the end, you check if your flag equal is true and do whatever you want to do.
How do you randomize an array using actionscript 3?
There is a short version using Array.sort() function:
var arr : Array = [0,1,2,3,4,5,6,7,8,9];
function randomize ( a : *, b : * ) : int {
return ( Math.random() > .5 ) ? 1 : -1;
}
trace( arr.sort( randomize ) );
If you don't get "enough" randomness you can sort twice :)
EDIT - explanation line by line:
For Array class method sort() you can pass not only sort options like Array.CASEINSENSITIVE, Array.DESCENDING and so on but also your own custom compare function reference (a callback) that accepts two parameters (two elements from array to compare). From AS3 documentation:
A comparison function should take two arguments to compare. Given the elements A and B, the result of compareFunction can have a negative, 0, or positive value:
A negative return value specifies that A appears before B in the sorted sequence.
A return value of 0 specifies that A and B have the same sort order.
A positive return value specifies that A appears after B in the sorted sequence.
Note: compare function parameters might be typed (if your array is typed) and have any name you want eg.:
function compareElements ( elementA : SomeClass, elementB : SomeClass ) : int;
This method is very useful when you need to sort array elements by their special properties. In randomization case compareFunction randomly returns -1, 0 or 1 and makes array elements to switch their places (indices). I have found that better randomization (in my subjective and mathematically untested opinion) is when method returns only -1 and 1. Also have in mind that sorting function with custom compare function doesn't compare elements sequentially so in some special cases randomization results may differ from what you might expect.
There's a better way that will also allow you to randomize the array in place, if you need that, and it will not make you create more then a single copy of your original array.
package
{
import flash.display.Sprite;
public class RandomizeArrayExample extends Sprite
{
public function RandomizeArrayExample()
{
super();
testDistribution();
}
private function testDistribution():void
{
var hash:Object = { };
var tester:Array = [1, 2, 3, 4];
var key:String;
for (var i:int; i < 1e5; i++)
{
randomize(tester);
key = tester.join("");
if (key in hash) hash[key]++;
else hash[key] = 1;
}
for (var p:String in hash) trace(p, "=>", hash[p]);
}
private function randomize(array:Array):Array
{
var temp:Object;
var tempOffset:int;
for (var i:int = array.length - 1; i >= 0; i--)
{
tempOffset = Math.random() * i;
temp = array[i];
array[i] = array[tempOffset];
array[tempOffset] = temp;
}
return array;
}
}
}
I had an alternative requirement where i wanted to randomly insert lots of source arrays into a target array randomly. Like Rytis i'm a big fan of the forEach, map and sort functions on Arrays.
var randomInsert:Function = function callback(item:*, index:int, array:Vector.<MyItem>):void
{
var j:Number = Math.floor(Math.random() * targetArray.length);
targetArray.splice(j,0,item);
}
targetArray = new Vector.<MyItem>();
sourceArray1.forEach(randomInsert, this);
sourceArray2.forEach(randomInsert, this);
here's an easier function. Works also on multidimensional arrays
function randomizeArray(array:Array):Array
{
var newArray:Array = new Array();
while (array.length > 0)
{
var mn=Math.floor(Math.random()*array.length)
newArray[newArray.length]=array[mn]
array.splice(mn,1)
}
return newArray;
}
I found this very helpful. I hope it can help you too.
// Array to Randomize
var firstArray:Array = ["One","Two","Three","Four","Five","six","seven","eight","nine","ten"];
trace(firstArray); // Prints in order
var newArray:Array = new Array();
function randomizeArray(array:Array):Array
{
var newArray:Array = new Array();
while (array.length > 0)
{
newArray.push(array.splice(Math.floor(Math.random()*array.length), 1));
}
return newArray;
}
var randomArray:Array = randomizeArray(firstArray);
trace(randomArray); // Prints out randomized :)
If you need your array to be shuffled (your elements can not repeat). You could use this function:
/**
* Shuffles array into new array with no repeating elements. Simple swap algorithm is used.
*/
public function shuffleArray(original:Array):Array
{
// How many swaps we will do
// Increase this number for better results (more shuffled array, but slower performance)
const runs:int = original.length * 3;
var shuffled:Array = new Array(original.length);
var i:int;
var a:int;
var b:int;
var temp:Object;
// Copy original array to shuffled
for(i=0; i<shuffled.length; i++){
shuffled[i] = original[i];
}
// Run random swap cycle 'runs' times
for(i=0; i<runs; i++){
// There is a chance that array element will swap with itself,
// and there is always small probability it will make your shuffle
// results not that good, hence try to experiment with
// different runs count as stated above
a = Math.floor(Math.random() * original.length);
b = Math.floor(Math.random() * original.length);
// Swap messages
temp = shuffled[a];
shuffled[a] = shuffled[b];
shuffled[b] = temp;
}
return shuffled;
}
Usage:
var testArray:Array = ["Water", "Fire", "Air", "Earth"];
trace(shuffleArray(testArray).concat());
this is how I randomize my array of 36 cards for a memory game
const QUANT_CARTAS: int = 36;
//get the 36 numbers into the array
for (var i: int = 0; i < QUANT_CARTAS; i++)
{
cartas.push(i);
}
//shuffles them =)
for (var moeda: int = QUANT_CARTAS - 1; moeda > 0; moeda--)
{
var pos: int = Math.floor(Math.random() * moeda);
var carta: int = cartas[moeda];
cartas[moeda] = cartas[pos];
cartas[pos] = carta;
}
// and add them using the random order...
for (i = 0; i < QUANT_CARTAS; i++)
{
var novaCarta: Carta = new Carta();
novaCarta.tipoCarta = cartas[i];
etcetcetc.............
}
choose random string from array
function keyGenerator(len:Number):String
{
function randomRange(minNum:Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
var hexArray = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
var key = "";
for (var i=0; i<len; i++)
{
key += hexArray[randomRange(0,hexArray.length-1)];
}
return key;
}
usage:
trace(keyGenerator(16));