wyc
wyc

Reputation: 55283

Building a simple randomizer which includes a dot, an underscore, the letter A and the letter B

Basically, I want to build a randomizer that can produce an output with following possible combinations:

.
. .
. . .
_
_ _
_ _ _
. _
_ .
. . _
_ . .
. _ _
_ _ .
_ . _
. _ .

and finally, preppend the letter A and B randomly at the beginning.

e.g.:

A . _
B _ _
A . . _
A _ .
B . _ _
A .

etc.

Any ideas of how to accomplish this with JavaScript?

Upvotes: 0

Views: 228

Answers (2)

Kevin B
Kevin B

Reputation: 95017

Here's another way: http://jsfiddle.net/8AHaw/

function makeid() {
    var text = "";
    var possibleChars = "._";
    var possibleLetters = "AB";

    text += possibleLetters.charAt(Math.floor(Math.random() * possibleLetters.length));
    for( var i=0; i < Math.floor(Math.random() * 3)+1; i++ )
        text += " " + possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));

    return text;
}

for (var i=0; i < 20; i++)
    $("body").append("<div>" + makeid() + "</div>");

Adapted from Generate random string/characters in JavaScript

Upvotes: 2

Esailija
Esailija

Reputation: 140228

var a = [
    ".",
    ". .",
    ". . .",
    "_",
    "_ _",
    "_ _ _",
    ". _",
    "_ .",
    ". . _",
    "_ . .",
    ". _ _",
    "_ _ .",
    "_ . _",
    ". _ ."
    ],

    b = ["A ", "B "];



    function getRandom() {
        return b[Math.random()*b.length|0] + a[Math.random()*a.length|0];
    }

    getRandom(); //"A ."
    getRandom(); //"A _ _ _"
    getRandom(); //"B . _ _"

With a loop:

var l = 20;
while(l--) console.log( getRandom() );

Upvotes: 2

Related Questions