jweinst1
2/6/2016 - 9:25 PM

random strings in javascript

random strings in javascript

//random generation of strings

//randomly selects value in array
function randselect(arr) {
    return arr[Math.floor((Math.random() * arr.length))];
}
//random letter
function randletter() {
    var letters = "abcdefghijklmnopqrstuvwxyz".split("");
    return randselect(letters);
}
//random string
function randAlphaString(len) {
    var newstr = "";
    for(var i=0;i<len;i++) newstr += randletter();
    return newstr;
}
//random string of alternating consonants and vowels
function randConVowString(len) {
    var cons = "bcdfghjklmnpqrstvwxyz".split("");
    var vow = "aeiou".split("");
    var newstr = "";
    for(var i =0;i<len/2;i++) newstr += randselect(cons) + randselect(vow);
    return newstr;
}
//randomly combines a prefix and suffix
function randPreSuffWord(prefixes, suffix) {
    return randselect(prefixes) + randselect(suffix);
}
//produces an alternating sequence of randomly selected strings from lists
function randFirstSecond(firsts, seconds, len) {
    var mode = "first";
    var newstr = "";
    for(var i=0;i<len;i++) {
        if(mode=="first") {
            newstr += randselect(firsts);
            mode = "second";
        }
        else {
            newstr += randselect(seconds);
            mode = "first";
        }
    }
    
}
//example decisions tree
var sym_tree = {
    "a":{
        "t": "aeu".split(""),
        "r": "aoi".split("")
    },
    "tr":{
        "a": {
            "b": "trff".split("")
        }
    }
};


//Random String generator that selects until search is found.

var randStringGenerator = function(strings, subs) {
    this.strings = strings;
    this.subs = subs;
    this.found = false;
    this.gen = function(len) {
        if(this.found) throw "Stop iteration";
        var newstr = "";
        for(var i=0;i<len;i++) newstr += randselect(this.strings);
        if(newstr.search(this.subs)!=-1) {
            this.found = true;
            return newstr;
        }
        else {
            return newstr;
        }
    };
};