Split a string into all possible combinations (Regex and Linq?)

Linq , Regex , split Montreal, Canada
  • 7 years ago

    Hello,

    Here is the challenge:

    Is there a way to split a string of minimum 4 : "abcd" and maximum 12: "abcdefghijklmnop" into all possible consecutive 4 combinations of maximum 3 elements?

    a.b.c.d - only 1 possibility for this one but for "abcdefgh": - a.bc.de.fgh - abc.d.e.fgh .... all possibilities

    Using REGEX and LINQ ?

    Thank you.

  • 7 years ago
        public static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<T> list)
        {
            if (list.Count() == 1)
                return new List<IEnumerable<T>> { list };
    
            return list.Select((a, i1) => Permute(list.Where((b, i2) => i2 != i1)).Select(b => (new List<T> { a }).Union(b)))
                       .SelectMany(c => c);
        }
    

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Theory is when you know something, but it doesn't work. Practice is when something works, but you don't know why. Programmers combine theory and practice: Nothing works and they don't know why.”