-1

I'd like get random letters together to generate weird words with a specified pattern like cvvcv (consonants and vowels). No consonant variations like th- sh- ch- etc needed.

The problem is, when I attempt to do one, I have to specify the length of the word. However, I want the number of characters in the output to be the same in the pattern. I mean the length would be pre-defined by the character number of the pattern.

An example with a fiddle would be great and much appreciated.

ofer dofer
  • 631
  • 2
  • 11
  • 28

2 Answers2

2

You can try this, too:

function replacePattern(pattern) {
    var possibleC = "BCDFGHJKLMNPQRSTVWXZ";
    var possibleV = "AEIOUY";

    var pIndex = pattern.length;
    var res = new Array(pIndex);

    while (pIndex--) {
       res[pIndex] = pattern[pIndex]
         .replace(/v/,randomCharacter(possibleV))
         .replace(/c/,randomCharacter(possibleC));
    }

    function randomCharacter(bucket) {
        return bucket.charAt(Math.floor(Math.random() * bucket.length));
    }   
    return res.join("").toLowerCase();
};

https://jsfiddle.net/u2aooqf7/

jenjis
  • 1,077
  • 4
  • 18
  • 30
0

If you managed to do that in C++ you shouldn't have a problem recreating that logic in JavaScript.

Anyway, I assembled a little snippet for you:

var createWordFromPattern = function(pattern) {
    var resultStack = [];
    for(var i=0; i<pattern.length; i++) {
        var sign = pattern.charAt(i);
        var signResult = getRandomSubstituteForSign(sign);
        if(signResult !== null) {
            resultStack.push(signResult);
        }
    }
    return resultStack.join("");
}

var getRandomSubstituteForSign = function(sign) {
    var vowels = ['a', 'e', 'i', 'o', 'u'];
    var consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l']; //just added some for demonstration
    
    if(sign === 'c') {
        return consonants[Math.floor(Math.random()*consonants.length)]
    }
    
    if(sign === 'v') {
        return vowels[Math.floor(Math.random()*vowels.length)]
    }
    
    return null;
}

document.write(createWordFromPattern("cvvcv"));

You can press Run code snippet a few times to see the results. It's very verbose and missing many consonants, but I think you get the idea of how to tackle this problem.

As this stands, it will turn cs in the pattern String to a random entry from the consonants array, and vs to a random entry from the vowels array. Every other character in the pattern string will be ignored.

This can easily be expanded by adding detection for more signs for example, but this is just to give you an idea about how to solve the problem.

kasoban
  • 2,107
  • 17
  • 24