How to find repeating sequence of Integers in an array of Integers?
00 would be repeating, so would 123123, but 01234593623 would not be.
I have an idea to h
Try this:
string lookIn = "99123998877665544123";
// above has length of 20 (in positions 0 through 19)
int patternLength = 3;
// want to search each triple of letters 0-2, 1-3, 2-4 ... 17-19
// however since there must be 3 chars after the 3-char pattern
// we only want to search the triples up to 14-16 (20 - 3*2)
for (int i=0; i <= lookIn.Length - patternLength * 2; i++) {
string lookingFor = lookIn.Substring(i, patternLength);
// start looking at the pos after the pattern
int iFoundPos = lookIn.IndexOf(lookingFor, i + patternLength);
if (iFoundPos > -1) {
string msg = "Found pattern '" + lookingFor
+ "' at position " + i
+ " recurs at position " + iFoundPos;
}
}
// of course, you will want to validate that patternLength is less than
// or equal to half the length of lookIn.Length, etc.
EDIT: improved and converted to javascript (from C# ... oops, sorry about that...)
function testfn() {
var lookIn = "99123998877665544123";
// above has length of 20 (in positions 0 through 19)
var patternLength_Min = 2;
var patternLength_Max = 5;
if (patternLength_Max > (lookIn.length / 2)
|| patternLength_Max < patternLength_Min
|| patternLength_Min < 1) {
alert('Invalid lengths.')
}
var msg = "";
for (var pLen = patternLength_Min; pLen <= patternLength_Max; pLen++) {
for (var i = 0; i <= lookIn.length - pLen * 2; i++) {
var lookingFor = lookIn.substring(i, i + pLen);
// start looking at the pos after the pattern
var iFoundPos = lookIn.indexOf(lookingFor, i + pLen);
if (iFoundPos > -1) {
msg = msg + "Found '" + lookingFor
+ "' at pos=" + i
+ " recurs at pos=" + iFoundPos + "\n";
;
}
}
}
alert(msg);
}
The message box displays the following:
Found '99' at pos=0 recurs at pos=5
Found '12' at pos=2 recurs at pos=17
Found '23' at pos=3 recurs at pos=18
Found '123' at pos=2 recurs at pos=17