question

Preet avatar image
1 Like"
Preet asked Natalie White commented

How to create random alphanumeric string in flexscript?

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.

FlexSim 23.1.2
random string generation
· 1
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

Natalie White avatar image Natalie White commented ·

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 0 ·

1 Answer

·
Carter Walch avatar image
1 Like"
Carter Walch answered Jason Lightfoot edited

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!


· 1
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

Jason Lightfoot avatar image Jason Lightfoot ♦ commented ·

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.

1 Like 1 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.