模式查找器算法

时间:2019-10-29 16:39:19

标签: algorithm

我想写一个能够检测任何模式并确定下一个元素的算法。例如,11 22 11 22 1的下一个元素是1。

但是也可能是3 1 1 1 1 3 3 3 1 1 1 3 3 3 1 1 1 1 (1x3 , 4x1, 3x3, 3x1, 3x3, 4x1),下一个元素将是3。

所以总是这样:3 1 1 1 1 3 3 3 1 1 1 3 3 3 1 1 1 1 3 1 1 1 1 3 3 3 1 1 1 3 3 3 1 1 1 1

我们不知道该模式有多长,但是我们知道它在数组中至少出现一次。我们也知道只有一个模式,其中的100%位于数组内部。

将数字想象为颜色可能有用,该阵列将是一面带有重复墙纸的墙。因此,我们的任务是确定如果连续的话墙会是什么颜色。

我应该如何开始?

2 个答案:

答案 0 :(得分:1)

只要模式始终在整个数组中重复,您就可以开始测试从数组开头到结尾的长度递增的模式,如果出现故障,则移动到下一个更大的长度,直到检查完整个数组为止,返回最短的成功模式。

类似于以下(未经测试的)JavaScript代码:

var findShortestRepeatingPattern = function(array){
  var pattern = [];

  for(var patternLength = 0; patternLength < array.length; length++){
    pattern = []
    var arrayCursor = 0;

    //Build the pattern from the start of the array
    while(arrayCursor < patternLength){
      pattern.push(array[arrayCursor++]);
    }

    //Test the pattern on the remainder of the array
    var patternMatches = true;
    while(arrayCursor < array.length){
      if(pattern[arrayCursor % patternLength] != array[arrayCursor++]){
        patternMatches = false;
        break;
      }
    }

    //Exit if the pattern matches
    if(patternMatches){
      break;
    }
  }

  return pattern;
};

然后,下一个期望值应该是索引insertIndex mod patternLength处的patternValue。

答案 1 :(得分:1)

您可以搜索字符串中其他任何地方都可以找到的最长后缀。与其简单地在其他位置添加后缀后面的字符。

示例 3 1 1 1 1 3 3 3 1 1 1 3 3 3 1 1 1 1

我们可以在序列的其他位置(比结尾处)查找以下后缀

1            (found at a lot of positions)   
1 1          (found at a lot of positions)  
1 1 1        (found at a lot of positions)  
1 1 1 1      (found at position 1)  
3 1 1 1 1    (found at position 0)  
3 3 1 1 1 1  (does not appear anywhere in the sequence except at  the end)  

因此,最长后缀为3 1 1 1 1,后跟3

3 1 1 1 1 3 3 3 1 1 1 3 3 3 1 1 1 1  
xxxxxxxxx ^

因此,下一个字符的估算规则为3