The goal is to find the longest repeating pattern, given a list. Being a bit new to C# I found a similar program but referring to Strings here:
https://www.javatpoint.com/program-to-find-longest-repeating-sequence-in-a-string
So far my code looks like this:
using System;
using System.Collections.Generic;
public class Solution
{
//Checks for the largest common prefix
public static List<int> lcp(List<int> s, List<int> t){
int n = Math.Min(s.Count,t.Count);
for(int i = 0; i < n; i++){
if(s[i] != t[i]){
return s.GetRange(0,i);
}
}
return s.GetRange(0,n);
}
public static void Main()
{
int[] use = {1,2,3,4,5,1,2};
List<int> list = new List<int>(use);
//List<int> sublist = list.GetRange(1, 4);
List<int> lrs = new List<int>();
int n = list.Count;
for(int i = 0; i < n; i++){
for(int j = i+1; j < n-i; j++){
//Checks for the largest common factors in every substring
List<int> x = new List<int> ();
x = lcp(list.GetRange(i,list.Count-1),list.GetRange(j,list.Count-1));
//If the current prefix is greater than previous one
//then it takes the current one as longest repeating sequence
if(x.Count > lrs.Count) lrs=x;
}
}
Console.WriteLine("Longest repeating sequence: "+lrs);
}
}
However I'm getting the following error and don't know how to fix it. I have messed around a bit with the indexes but can't figure it out:
Unhandled Exception: System.ArgumentException: index and count exceed length of list at System.Collections.Generic.List`1[System.Int32].CheckRange (Int32 idx, Int32 count) [0x00000] in <filename unknown>:0 at System.Collections.Generic.List`1[System.Int32].GetRange (Int32 index, Int32 count) [0x00000] in <filename unknown>:0 at Solution.Main () [0x00000] in <filename unknown>:0 [ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentException: index and count exceed length of list at System.Collections.Generic.List`1[System.Int32].CheckRange (Int32 idx, Int32 count) [0x00000] in <filename unknown>:0 at System.Collections.Generic.List`1[System.Int32].GetRange (Int32 index, Int32 count) [0x00000] in <filename unknown>:0 at Solution.Main () [0x00000] in <filename unknown>:0