Domanda

I've been struggling with this for a week.

I have a string like this: 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1.....

What I need to find: 1 1 0


example 2: 1 1 2 0 2 2 1 0 1 1 2 0 2 2 1 0 1 1 2 0 2 2 1 0 1 1 2 0 2 2 1 0 ....

What I need to find: 1 1 2 0 2 2 1 0


example 3: 1 1 2 3 1 0 1 1 2 3 1 0 1 1 2 3 1 0 1 1 2 3 1 0 1 1 2 3 1 0...

112310


etc. etc.

My code as now:

private string tekrarArama(double[] mods)
        {
            string part1 = "";
            string part2 = "";

            string patern = "";


            int number1 = mods.Length;

            for (int i = 0; i < mods.Length; i++)
            {
                part1 = "";
                part2 = "";
                for (int j = 0; j < number1; j++)
                {

                    part1 += mods[j] + ",";
                }


                for (int k = 0; k < mods.Length; k++)
                {

                    part2 += mods[k] + ",";
                }


                int actualcount = Regex.Matches(part2, part1).Count;

                int count = part2.Replace(",", "").Length / part1.Replace(",", "").Length;


                if (part2.IndexOf(bolum1) >= 0 && actualcount == count )
                {
                    patern = part2.Substring(part2.IndexOf(part1),part1.Length);
                }

                number1--;


            }

            return patern;

        }

It creates two copies of the string and deletes 1 character at a time from one of the strings in each iteration, to find the smallest repeating pattern.

It's a mess and doesn't work very well at all. How can I do this? Thanks in advance.

È stato utile?

Soluzione

If you're looking for something simple and don't need optimal complexity, here's a concise way to represent the query.

string FindPattern(string text)
{
    if (text == null)
    {
        return null;
    }

    return Enumerable
        .Range(1, text.Length / 2)
        .Where(n => text.Length % n == 0)
        .Select(n => text.Substring(0, n))
        .Where(pattern => Enumerable
            .Range(0, text.Length / pattern.Length)
            .SelectMany(i => pattern)
            .SequenceEqual(text))
        .FirstOrDefault();
}

Note that the complexity here is quadratic in the worst case, so it's not a good idea to use it for very long strings.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top