Con*_*sea 0 java arrays algorithm math
如何在整数数组中找到重复的整数序列?
00 会重复,123123 也会重复,但 01234593623 不会。
我有一个如何做到这一点的想法,但我的想法很模糊,因此我的实现并没有走多远。
我的想法是
在 Java 中,我做到了这一点:
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");
}
Run Code Online (Sandbox Code Playgroud)
当使用这些参数运行时:
repeatingSeqOf(2, new String[] {"1", "2", "3", "4", "5", "6", "7", "7" });
Run Code Online (Sandbox Code Playgroud)
我正确地填充了节数组,但它在索引越界异常时中断。
@MiljenMikic 的回答很棒,尤其是因为语法实际上并不规则。:D
如果你想在一个数组上做一般的事情,或者想理解它,这几乎和正则表达式所做的完全一样:
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)