An algorithm for randomly breaking words into specific length groups

I am writing a program (in JavaScript) that should randomly split a string (one word) into groups of letters, each group length (number of characters) being 2-3 or 4 characters. For example, it australiamay return:

aus
tral
ia

or

au
str
alia

I am currently doing this “manually”, with if statements for each line length, for example:

if (word.length == 4){ //split
    sections.push(word.substr(0,2));
    sections.push(word.substr(2,4));
}

if (word.length == 5){ //either 2/3 or 3/2
    if (randomBetween(1,2) == 1){
        sections.push(word.substr(0,2));
        sections.push(word.substr(2,5));
    } else {
        sections.push(word.substr(0,3));
        sections.push(word.substr(3,5));
    }
}

etc...

// randomBetween(x,y) randomly returns one of the arguments

Does anyone have a more algorithmic solution?

+4
source share
2 answers

Select a random length of 2 to 4 iteratively to form a list of groups. Trim the edges when the remaining line is too small to have all of these options.

, . , .

, , , 2.

function randomlySplit(word) {
    var groups = [],
        tail = word;
    while (tail.length) {
        var availableLengths = [2, 3, 4];
        if (tail.length <= 3) availableLengths = [tail.length];
        if (tail.length === 4) availableLengths = [2];
        if (tail.length === 5) availableLengths = [2, 3];
        var length = availableLengths[(Math.random() * availableLengths.length) | 0];
        groups.push(tail.slice(0, length));
        tail = tail.slice(length);
    }
    return groups;
}
alert(randomlySplit("australia"));
Hide result

jsFiddle.

+2

, , .

function randomlySplit(word) {
    var parts = [];
    // Loop as long as word exists
    while(word.length) {
        // Get an integer which is 2,3 or 4
        var partLength = Math.floor(Math.random() * 3 + 2);
        // See if only 1 char would be left
        if(word.length - partLength === 1) {
            // Either add or subtract 1 to partLength
            if(partLength < 4) partLength++;
            else partLength--;
        }
        // No issue that partLength > word.length
        parts.push(word.substring(0,partLength));
        word = word.substring(partLength);
    }
    return parts;
}
alert(randomlySplit("australia"));
Hide result
+1

All Articles