简体   繁体   English

在Java中的整数数组中找到模式长度?

[英]finding the pattern length in an integer array in java?

Suppose I have a Fibonacci sequence of the number x as follows and I want to detect a sequence in an array. 假设我有一个x的斐波那契数列,如下所示,我想检测一个数组中的数列。 Java method should return the length of sequence Java方法应返回序列的长度

   x         0  1  1  2  3  5  8  13  21  34  55  89  144  233  377  610
 1)x mod 2 - 0  1  1  0  1  1  0   1   1   0   1   1    0    1    1    0
 2)x mod 3 - 0  1  1  2  0  2  2   1   0   1   1   2    0    2    2    1

 Answer 1) 3 (repetitive sequence 011 and length is 3)
        2) 8 (repetitive sequence 01120221 and length is 8)

A very simple approach would be to create a copy of the array, and check position 0 of the first array against position 1 of the second array, and if they match, continue checking until the end. 一种非常简单的方法是创建该数组的副本,然后将第一个数组的位置0与第二个数组的位置1进行检查,如果它们匹配,则继续检查直到结束。 If the whole thing matches, then you have a repeating length of 1. 如果整体匹配,则重复长度为1。

If not, then you compare position 0 of the first array to position 2 of the second array, and follow the same process as above. 如果不是,则将第一个数组的位置0与第二个数组的位置2进行比较,然后执行与上述相同的过程。 If this matches, then you have a repeating length of 2. 如果匹配,则重复长度为2。

And you continue this process until you either find a match, or reach the end of the array and can't offset it any further, in which case there is no repeat. 然后继续此过程,直到找到匹配项,或者到达数组的末尾并且无法再进行偏移,在这种情况下就不再重复。

If you are only intending to use this specifically for modulo values of numbers in the Fibonacci sequence, and not for arbitrary data, then the sequence will repeat as soon as you find the second occurrence of a 0 followed by a 1 in the modulo sequence. 如果仅打算将其专门用于斐波那契数列中数字的模值,而不是用于任意数据,则该序列将在您发现模数序列中第二次出现0且后跟1时重复。 This is because mod(a + b, n) = mod(mod(a, n) + mod(b, n), n), so the modulo of a number in the Fibonacci sequence (which is the sum of the two previous values) is determined by the previous 2 modulo results. 这是因为mod(a + b,n)= mod(mod(a,n)+ mod(b,n),n),所以斐波那契数列中数字的模数(前两个数之和)值)由之前的2个模结果确定。 Therefore, once the original pattern of a 0 followed by a 1 reoccurs, the pattern will repeat. 因此,一旦再次出现原始的模式0和1之后,该模式将重复。

The Following code works: 以下代码有效:

    private static int detectSequence(int[] array) {

    int count = 2;
    for (int i = 2; i < array.length; i++) {
        if(array[i] == 0 && array[i+1] == 1 && i+1 < array.length){
            return count;
        }
        count++;
    }
    return count;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM