RSS LinkedIn Twitter

Generating Random Strings with ActionScript

March 10th, 2011 Categories: Actionscript, Flex 3, Flex 4

Here’s a pair of methods I use to generate random usernames for an online test. They could be used to generate random strings for any purpose, though.

len is the length of the random string you want returned.

WP-SYNHIGHLIGHT PLUGIN: NOTHING TO HIGHLIGHT! PLEASE READ README.TXT IN PLUGIN FOLDER!
public static function generateRandomString(len:uint = 1, userAlphabet:String = "abcdefghijklmnopqrstuvwxyz"):String{
var alphabet:Array = userAlphabet.split("");
var alphabetLength:int = alphabet.length;
var randomLetters:String = "";
for (var i:uint = 0; i < len; i++){ randomLetters += alphabet[int(Math.floor(Math.random() * alphabetLength))]; } return randomLetters; } [/codesyntax] [codesyntax lang="actionscript3" tab_width="2" blockstate="expanded"] public static function generateRandomNumber(len:uint = 1, userAlphabet:String = "0123456789"):String{ var alphabet:Array = userAlphabet.split(""); var alphabetLength:int = alphabet.length; var randomNumbers:String = ""; for (var i:uint = 0; i < len; i++){ randomLetters += alphabet[int(Math.floor(Math.random() * alphabetLength))]; } return randomNumbers; } [/codesyntax] There's no need to point out that the generateRandomNumber method could be optimized. I know. My specific use case called for a string of 4 characters followed by a 3 digit number. If you weren't restricted to that, there's no reason you couldn't combine the two 'alphabets'. In fact, you could include other characters if you were trying to generate a strong password.

Tags:
No comments yet.

Leave a Comment

*