The following codes are written in ES6. You can make a sliding
procedure which takes a string input a returns an Iterable of substring "windows"
Array.from(sliding (3,1) ('012345'))
// [ '012', '123', '234', '345' ]
Array.from(sliding (2,2) ('012345'))
// [ '01', '23', '45' ]
Array.from(sliding (4,2) ('012345'))
// [ '0123', '1234', '2345' ]
Then, using this, you can define a seqIsRepeated
procedure which iterates thru the sliding windows. Instead of pre-computing the entire list of windows, we will look at them 1-by-1, adding each result to a Set. If the window already exists in the Set, true
will be returned immediately and iteration is stopped. If the procedure makes it thru all windows without finding a duplicate, false
will be returned.
const sliding = (m,n) => function* (xs) {
for (let i = 0; i + m <= xs.length; i += n)
yield xs.substr(i, m);
};
const seqIsRepeated = n => xs => {
let set = new Set();
for (let seq of sliding (n,1) (xs))
if (set.has(seq))
return true;
else
set.add(seq);
return false;
};
console.log (seqIsRepeated (3) ('0102340109')); // true
console.log (seqIsRepeated (3) ('0002223589765')); // false
This doesn't find you the longest sequence, but hopefully it does give you a start. From here, you'd be looking at substrings of your input sequence and using seqIsRepeated(3)
to eliminate substrings as possibilities