如何在整数数组中找到重复的整数序列? [英] How to find repeating sequence of Integers in an array of Integers?
问题描述
如何在整数数组中找到重复的整数序列?
How to find repeating sequence of Integers in an array of Integers?
00将重复,123123也是如此,但01234593623不会重复。
00 would be repeating, so would 123123, but 01234593623 would not be.
我知道如何做到这一点,但在我看来它很模糊,而且由于这个原因,我的实施并不顺利。
I have an idea to how to do this, but it is blurry in my mind, and my implementation doesn't go far due to this.
我的想法是
- 每次进行for循环时抵消一定金额
- 在其中循环并比较那个偏移的数字块
在Java中,我得到了这个:
In Java, I got this far:
String[] p1 = new String[nDigitGroup];
String[] p2 = new String[nDigitGroup];
for (int pos = 0; pos < number.length - 1; pos++)
{
System.out.println("HERE: " + pos + (nDigitGroup - 1));
int arrayCounter = -1;
for (int n = pos; n < pos + nDigitGroup ; n++)
{
System.out.printf("\nPOS: %d\nN: %d\n", pos, n);
arrayCounter++;
p1[arrayCounter] = number[n];
System.out.println(p1[arrayCounter]);
}
pos += nDigitGroup;
arrayCounter = -1;
System.out.println("SWITCHING");
for (int n = pos; n < pos + nDigitGroup ; n++)
{
System.out.printf("\nPOS: %d\nN: %d\n", pos, n);
arrayCounter++;
p2[arrayCounter] = number[n];
System.out.println(p2[arrayCounter]);
}
if (p1[0].equals(p2[0]) && p1[1].equals(p2[1])) System.out.println("MATCHING");
}
使用这些参数运行时:
repeatingSeqOf(2, new String[] {"1", "2", "3", "4", "5", "6", "7", "7" });
我正在填充节数组,但它在索引超出范围异常时中断。
I am correctly filling the section arrays, but it breaks on an index out of bounds exception.
推荐答案
@MiljenMikic答案很棒,特别是因为语法实际上不是常规的。 :D
@MiljenMikic answer's is great, especially since the grammar isn't actually regular. :D
如果你想在一般的数组上做这个,或者想要理解它,这几乎就是正则表达式所做的:
If you want to do it on an array in general, or want to understand it, this does pretty much exactly what the regex does:
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3, 2, 3}; // 2, 3 repeats at position 2.
// for every position in the array:
for (int startPos = 0; startPos < arr.length; startPos++) {
// check if there is a repeating sequence here:
// check every sequence length which is lower or equal to half the
// remaining array length: (this is important, otherwise we'll go out of bounds)
for (int sequenceLength = 1; sequenceLength <= (arr.length - startPos) / 2; sequenceLength++) {
// check if the sequences of length sequenceLength which start
// at startPos and (startPos + sequenceLength (the one
// immediately following it)) are equal:
boolean sequencesAreEqual = true;
for (int i = 0; i < sequenceLength; i++) {
if (arr[startPos + i] != arr[startPos + sequenceLength + i]) {
sequencesAreEqual = false;
break;
}
}
if (sequencesAreEqual) {
System.out.println("Found repeating sequence at pos " + startPos);
}
}
}
}
这篇关于如何在整数数组中找到重复的整数序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!