Results 1 to 4 of 4
  1. #1

    Generating random letters

    More help needed please.

    I have the following script that generates a string of the letter "a" depending on the value in maxSize. Now I need to change this so the value of "a" in 'text = text + "a"' is a random value of a - z.

    Can anyone advise how to do this.

    // This function returns a string of length "maxSize" as pass by parameter
    // that contain lots of "a"s. E.g. GetStringOfLength(5) = "aaaaa";

    function GetStringOfLength(maxSize)
    var i, text = "";
    for(i = 0; i < maxSize; i++)
    text = text + "a";
    return text;

  2. #2

    Re: Generating random letters

    Hi Oompa

    It looks like you're using JScript, so you can add a Math.random statement to your function, like this:

    function GetStringOfLength(maxSize)
    var i,text="";
    //The below line generates a random number between 0 and the maxSize
    var randNum= Math.floor(Math.random()*maxSize);
    var randomLength = maxSize - randNum;
    for (i=0;i<randomLength,i++)
    text = text + "a";
    return text;

    There's a nice tutorial on the random method here:

    Hope this helps,

  3. #3
    Senior Member
    Join Date
    Apr 2006
    ked up until rehabilitated

    Re: Generating random letters


    This gives you the following code That would replace your line:

    text = text + "a";


    text = text + String.fromCharCode(97 + Math.round(Math.random() * 25));

    Where 97 = "a", and the rand will give you a value from 0 to 25.

    I hope this helps,
    Aaron Fager
    Software Test Engineer

    If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization.

  4. #4

    Re: Generating random letters

    Thanks guys.

    Both worked fine, I replaced text = text + "a" with the follwing in two new scripts:

    //Random number between 1 - 9
    text = text + Math.round(9*Math.random())

    //Random letter between a - z
    text = text + String.fromCharCode(97 + Math.round(Math.random() * 25));



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
BetaSoft Inc.
All times are GMT -8. The time now is 05:55 PM.

Copyright BetaSoft Inc.