【问题标题】:Permute string until it matches some input?置换字符串直到它匹配一些输入?
【发布时间】:2015-11-24 07:21:33
【问题描述】:

我在网上查了一下,没有太多结果,因为很难用几句话来描述。

基本上,我需要一个函数,比如puntil,它接受参数string。基本上,函数置换,直到字符串等于参数。

例如,如果您运行puntil('ab'),它应该在函数内部执行:

一个 b C d e F G H 一世 j ķ l 米 n ○ p q r s 吨 你 v w X 是的 z 啊 ab !!匹配

另一个例子,puntil('abcd') 可以

一个 b C d e F G H 一世 j ķ l 米 n ○ p q r s 吨 你 v w X 是的 z 啊 抗体 交流 广告 ae af 银 啊 艾 aj ak 人 是 一个 敖 ap 水 阿尔 作为 在 澳大利亚 影音 啊 斧头 是的 阿兹

...等等等等.. 直到匹配 abcd。

在匹配之前基本上是一个无限排列。

有什么想法吗?

【问题讨论】:

  • 你能把你的问题描述清楚吗?
  • @F.Ju 匹配宇宙中每一个可能的字符串,直到它匹配某个输入。
  • 我觉得很清楚了。
  • 那么,o/p 是什么? i/p 字符串之前的词条数还是我们需要在获得匹配字符串之前打印所有字符串?
  • @vish4071 好的,按照您的描述实现,您的目标是什么?或者你需要的是如何实现?

标签: javascript algorithm permutation


【解决方案1】:

这里是fiddle

 var alphabet = ['a','b','c'];//,'d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];

 var output = "";
 var match = "cccc";  //<----------- match here

//This is your main function 
function permutate() {

    var d = 0;   // d for depth

    while (true) {

       //Your main alphabet iteration             
       for (var i=0; i<alphabet.length; i++){

          //First level 
          if (d === 0) {
             console.log(alphabet[i])
             output = alphabet[i];
          }    
          else
             iterator(alphabet[i], d);   //Call iterator for d > 0

          if (output === match)
             return;
          }


          d++;  //Increase the depth
       }
 }


 //This function runs n depths of iterations
 function iterator(s, depth){

    if (depth === 0)
       return;

    for (var i=0; i<alphabet.length; i++){

       if (depth > 1)
          iterator(s + alphabet[i], depth - 1)
       else {
          console.log(s + alphabet[i]);
          output = s + alphabet[i];
       } 

       if (output === match)
          return;
    }

 };                

解释:

你的程序需要像这样遍历一棵字母树

[a] 
    -[a]
        -[a] 
             -[a]...
             -[b]...

         [b] ...
    -[b] -
         -[a]...
         -[b]...

[b] - ...
[c] - ...

如果不是因为您需要先完成每个深度的要求,这可以通过传统的递归函数轻松完成。

所以我们需要一个特殊的iterator(s, depth) 函数,它可以执行请求的嵌套迭代次数(深度)。

所以主函数可以调用深度递增的迭代器(d++)。

就是这样!!

警告:这只是一个原型。这可以优化和改进。为了便于演示,它使用全局变量。你的真实程序应该避免使用全局变量。如果匹配词太长,我还建议在setTimeout 中调用iterator()。 n 的深度只能受您的资源限制。

【讨论】:

  • 谢谢,这真的很好!我感谢努力! :D
  • 避免使用全局变量。让迭代器函数有它自己的字母数组。这是完全值得的。还将匹配词沿参数列表传递。提示:您甚至可以缩短此代码。为了便于解释,我打破了第一级和其余的。感谢您发布此信息。我玩得很开心。
【解决方案2】:

Fiddle here

function next(charArray, rightBound){

    if(!rightBound){
        rightBound = charArray.length;
    }

    var oldValue = charArray[rightBound-1];
    var newValue = nextCharacter(charArray[rightBound-1]);
    charArray[rightBound-1] = newValue;

    if(newValue < oldValue){
        if(rightBound > 1){
            next(charArray, rightBound-1);
        }
        else{
            charArray.push('a');
        }
    }
    return charArray;
}

function nextCharacter(char){
    if(char === 'z'){
        return 'a'
    }
    else{
        return String.fromCharCode(char.charCodeAt(0) + 1)
    }
}

function permuteUntil(word){
    var charArray = ['a'];
    var wordChain = ['a'];

    while(next(charArray).join('') !== word){
        wordChain.push(charArray.join(''));
    }

    wordChain.push(word);

    return wordChain.join(', ');
}


alert(permuteUntil('ab'));

【讨论】:

  • 谢谢,就这样...还有更优雅的方式吗?
  • 我已经用更简洁的代码更新了答案和小提琴
  • 谢谢!看起来你得到了我需要的东西......请稍等我为我的应用程序测试它:D
【解决方案3】:

OP 的要求有点模棱两可,所以我会针对 OP 要求的(我怀疑的)两件事发布。

首先,问题可能是,输入字符串在字母的无限排列中的位置是什么(我认为这是更合理的问题,我稍后会给出原因)。这可以通过以下方式完成:

举个例子(输入=dhca)。因此,所有 1 到 3 个字符长度的字符串都将出现在该字符串之前。所以,在答案中添加:26^1 + 26^2 + 26^3。那么,第一个字符是d,这意味着,按照字典,如果第一个字符是a | b | c,那么所有过去的字符都是有效的。因此,将3 * 26^3 添加到答案中。现在,假设第一个字符是d。然后,我们可以拥有来自a to g (7) 的所有字符,最后两个字符可以是任何字符。因此,将7 * 26^2 添加到答案中。这样下去,我们得到的答案是:

26^1 + 26^2 + 26^3 + (3 * 26^3) + (7 * 26^2) + (2 * 26^1) + (0) + 1
= 75791

好的。现在是第二件事,我认为 OP 实际上是在要求(在我们得到匹配之前打印所有字符串)。现在,为什么我认为这是不可行的,因为如果我们输入为zzzzz(5 个字符长),我们需要打印26^1 + 26^2 + 26^3 + 26^4 + 26^5 字符串,即12356630。因此,对于这一部分,我假设输入字符串的最大长度为 5(绝对不会更多),因为对于 6 个字符长度的字符串,我们需要打印 ~321272406 个字符串 --> 不可能。

所以,一个简单的解决方案可以是:

  • 创建一个大小为 27 的数组:arr[] = {'', 'a', 'b', ..., 'y', 'z'}。第一个字符为空。
  • 从 0 到 26(含)写入 5 个(最大字符串长度)嵌套循环,并将其添加到虚拟字符串并打印。类似的东西。

    for i from 0 to 26
        String a = "" + arr[i]
        for j from 0 to 26
            String b = a + arr[j]
            for k from 0 to 26
                String c = b + arr[k]
                for l from 0 to 26
                    String d = c + arr[l]
                    for m from 0 to 26
                        String e = d + arr[m]
                        print e
                        if(e equals input string)
                            break from all loops //use some flag, goto statement etc.
    

【讨论】:

  • 感谢您的回答:D。无论如何,如何在不使用输入字符串长度的情况下进行置换?就像盲置换一样,直到它与输入匹配。
  • 这个问题有比这个答案更好的解决方案。您可以使用递归循环来获得结果。深度仅受系统资源限制。
  • 您的问题所问的并不完全是排列。你有重复的字符,你需要的是 i/p 字符串的字典出现。
  • @bytec0de,我真的不明白所有这些字符串的用例是什么。同时,您不知道输入的最大长度是多少...即使使用最好的机器,对于长度为 7 的字符串,例如 zzzzzzz,您需要打印 8353082582 字符串,即至少需要 100 秒。正如@CharlieH 所说,使用递归代码,我认为系统堆栈不允许 8 阶深度,而我们正在谈论 10 阶。
【解决方案4】:

您要求一个更优雅的解决方案,这里有一个简单的函数,可以将整数转换为小写字符串,让您可以轻松地遍历字符串。

function toWord(val, first, out) {
if(first == 1)
    out = String.fromCharCode(97 + val % 26) + out;
else
    out = String.fromCharCode(97 + (val-1) % 26) + out;
if(val % 26 == 0 && first == 0) {
    val -= 26;
}
else {
    val -= val %26;
}
val = val / 26;
if(val != 0)
    return toWord(val, 0, out);
else
    return out;
}

它绝不是完美的,但它简短而简单。调用函数时设置val为要转换的整数,先为1,输出为""。

例如,以下代码会将 yourFunction 应用于前 10,000 个小写字符串

for(int i=0; i<10000; i++) {
    youFunction(toWord(i, 1, ""));
}

【讨论】:

    【解决方案5】:

    所以您需要始终从a 开始递增吗?由于它们是 char 值,因此您可以使用以下构造轻松做到这一点:

    请注意,这是一个 java 解决方案 :)

    public static char[] increment(char[] arr, int pos) {
        // get current position char
        char currentChar = arr[pos];
    
        // increment it by one
        currentChar++;
    
        // if it is at the end of it's range
        boolean overflow = false;
        if (currentChar > 'Z') {
            overflow = true;
            currentChar = 'A';
        }
    
        // always update current char
        arr[pos] = currentChar;
        if (overflow) {
            if (pos == 0) {
                // resize array and add new character
                char[] newArr = new char[arr.length + 1];
                System.arraycopy(arr, 0, newArr, 0, arr.length);
                newArr[arr.length] = 'A';
    
                arr = newArr;
            } else {
                // overflowed, increment one position back
                arr = increment(arr, pos - 1);
            }
        }
    
        return arr;
    }
    
    
    public static void main(String[] args) {
        final String stringToUse = "A";
        final String stringToSearch = "ABCD";
    
        char[] use = stringToUse.toCharArray();
        for (;;) {
            final String result = new String(use);
    
            System.out.println("Candidate: " + result);
            if (stringToSearch.equals(result)) {
                System.out.println("Found!");
                break;
            }
    
            use = increment(use, use.length - 1);
        }
    }
    

    【讨论】:

    • 感谢您的努力,看来这需要一些时间来思考...我没有使用 java 的经验,但这有助于可视化流程。谢谢!
    • @bytec0de,很棒的人,很高兴它有帮助,我也玩得很开心
    猜你喜欢
    • 2013-09-06
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2012-11-24
    • 2017-08-15
    相关资源
    最近更新 更多