用于将单词随机分成定义的长度组的算法

时间:2014-09-22 20:07:49

标签: javascript algorithm

我正在编写一个程序(在JavaScript中),它需要将一个字符串(一个单词)随机分成几组字母,每组长度(字符数)为2,3或4个字符长。例如,australia可以返回:

aus
tral
ia

au
str
alia

目前我正在这样做"手动",每个字符串长度的if语句,例如:

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

有没有人有更多的算法解决方案?

2 个答案:

答案 0 :(得分:2)

迭代地选择2到4的随机长度以形成组列表。当剩余的字符串太小而无法使用所有这些选项时处理边缘情况。

请注意,并非所有可能的组合都会以统一的概率选择。我不认为有效地做到这一点很简单。

如果传入长度小于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"));

您可以看到this in action on jsFiddle

答案 1 :(得分:1)

我为你做了一个评论函数,我希望它能帮助你。

&#13;
&#13;
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"));
&#13;
&#13;
&#13;