Domanda

What happens is that if a user clicks on the 'Get Session Id' button. It displays a random string which will represent the sessionId. This works fine. My problem is that at moment I have 5 strings which are "AAA", "AAB", "AAC", "AAD" and "AAE". Now I want the strings to go on all the way to "ZZZ".

It will take me an age and a lot of coding to write out all of the strings from "AAA" to "ZZZ". What I want to know is that is there a way where I can display all the strings between "AAA" and "ZZZ" without requiring entering in all of the strings manually?

Below is my code:

<head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title>Create a Session</title>
        <script type="text/javascript">

var randomStrings = [
        "AAA",
        "AAB",
        "AAC", 
        "AAD",
        "AAE",
    ];

    function getSession() {

var randomDiv = document.getElementById("randomStrings");

          randomIndex = Math.round(Math.random()*(randomStrings.length-1));
          newText = randomStrings[randomIndex];
          randomDiv.innerHTML = newText;
}

</head>

<body>
<form action="create_session.php" method="post" name="sessionform">
 <table>
          <tr>
          <th>1: </th>
          <td><input id="sessionBtn" type="button" value="Get Session ID" name="sessionid" onClick="getSession()" /></td>   <!-- Get Session ID here-->
          <td id="randomStrings"></td>
          </tr>
          </table>
</form>
</body>
È stato utile?

Soluzione

For what you're doing here, it will be way more expensive than necessary to generate all the possible strings, then choose one randomly. If you do it that way, you will have to generate 17,576 (26^3) strings, just for a single random three-letter string. You can, instead, just generate a single random string instead, one character at a time.

var alphabet = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ];

function generateRandomString(strLength) {
    var output = "";
    for (var i = 0; i < strLength; i++) {
        var randomIndex = Math.floor(Math.random() * alphabet.length);
        output += alphabet[randomIndex];
    }
    return output;
}

function getSession() {
    var randomDiv = document.getElementById("randomStrings");
    newText = generateRandomString(3);
    randomDiv.innerHTML = newText;
}

This solution also scales way better. To generate all the possible strings and choose one, your runtime would be O(26^n), where n is the number of characters in the string. The runtime of this solution (building the string character by character) is O(n), where n is the number of characters in the string.

This means if you decide you need more session IDs (if more users are using your application), you can do so easily. A 5-character session ID would take 11,881,376 iterations, if you were to build all the possibilities beforehand. It would take 5 iterations building one possibility on-the-fly.

Altri suggerimenti

function randLetter()
{
    return String.fromCharCode(65 + Math.round(Math.random()*25));
}

...

var newText = randLetter() + randLetter() + randLetter();

Just use a function like that.

http://jsfiddle.net/kgjcE/

this function works:

function getStrings(){
    var strings = [];
    var start = 65;
    var end = 91;
    for (var a = start; a < end; a++) {
            for (var b = start; b < end; b++) {
                    for (var c = start; c < end; c++) {
                            strings.push(String.fromCharCode(a)+String.fromCharCode(b)+String.fromCharCode(c));
                    }
            }
    }
    return strings;
}

but the answer from Jonathan Newmuis is much better.

Don't store all possible combinations in an Array.

Just generate the strings you want.

function gen_str( len ) { 
    var str = '';
    while( len-- )
        str += String.fromCharCode( ~~(Math.random() * 26) + 65 );
    return str;
}

var rand_str = gen_str( 3 );  // "AHY"

Here's a slight enhancement/simplification to Jonathan's function:

var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

function generateRandomString(strLength) {
    var output = "";
    for (var i = 0; i < strLength; i++) {
        var randomIndex = Math.floor(Math.random() * alphabet.length);
        output += alphabet.charAt(randomIndex);
    }
    return output;
}

function getSession() {
    var randomDiv = document.getElementById("randomStrings");
    newText = generateRandomString(3);
    randomDiv.innerHTML = newText;
}

Try this

http://jsfiddle.net/snJeX/

var strings = [];
for (var a = 0x41; a < 0x5b; a++) {
    for (var b = 0x41; b < 0x5b; b++) {
        for (var c = 0x41; c < 0x5b; c++) {
            strings.push(
                String.fromCharCode(a) +
                String.fromCharCode(b) +
                String.fromCharCode(c));
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top