How to create random alphanumeric string in flexscript?

How to create random alphanumeric string in flexscript?

preetdesai
Not applicable
48 Views
3 Replies
Message 1 of 4

How to create random alphanumeric string in flexscript?

preetdesai
Not applicable

[ FlexSim 23.1.2 ]

How to generate random string that contains alphanumeric characters with specified number of length of the string. Example are ckd938, jfp393 etc if we need the length of the string to be 6.

Accepted solutions (1)
49 Views
3 Replies
Replies (3)
Message 2 of 4

carter-walch
Not applicable
Accepted solution

Hi @Preet ,

alphanumericDemo.fsm

You could do something like this to make a six digit alphanumeric string randomly. You can adjust the numLetters and numNumbers variables depending on the length of the string you want. Example output below.

string letters = "abcdefghijklmnopqrstuvwxyz";
int numLetters = 3;
int numNumbers = 3;
string result = "";

//append the letters
for (int i = 0; i < numLetters; i++) {
    int randomIndex = duniform(1,26);
    string newChar = letters.charAt(randomIndex);
    result = result + newChar;
    //print(newChar);
}
//append the numbers
for (int i = 0; i < numNumbers; i++) {
    int randomNum = duniform(0,9);
    string newChar = string.fromNum(randomNum);
    result = result + newChar;
    //print(newChar);
}


print(result);

1688614637530.png

Hope that helps!

Message 3 of 4

jason_lightfootVL7B4
Autodesk
Autodesk

An alternative:

string result;
Array mix=[3,3]; // 3 letters, 3 numbers
for (int n=mix[1];n>0;n--)
    result+=strascii(duniform(97,122));  // for capitals use 64-90
result+=string.fromNum(duniform(1,Math.pow(10,mix[2])-1),0).padStart(3,"0"); 
return result;

For both approaches you should add a stream to duniform. If this is to become a user command, pass one in as parameter.

Message 4 of 4

natalie_white
Not applicable

Hi @Preet, was Carter Walch's answer helpful? If so, please click the "Accept" button at the bottom of their answer. Or if you still have questions, add a comment and we'll continue the conversation.

If we haven't heard back from you within 3 business days we'll auto-accept an answer, but you can always comment back to reopen your question.

0 Likes