TransWikia.com

split sequences

Stack Overflow Asked by Backgroup on December 30, 2021

I have a list List<int> myList = new List<int>(){1, 2, 3, 5, 6, 8, 12, 18, 19, 31};

What I’m trying to do is to split the sequences that occur.

For Example
In the above list I have 1, 2, 3 number in sequence
what I need is something that find the number in sequence and return something like this:

number 1 sequence 2.
number 5 sequence 1.
number 8 sequence 0.
number 12 sequence 0.
number 18 sequence 1.
and so on...

What I have tried so far

for (int i = 1; i < myList.Count; i++)
        {
            if (myList[i - 1] + 1 == myList[i])
            {
                count++;
            }
            else
            {
                if (count != 0)
                {
                    Console.WriteLine( myList[i - count - 1].ToString() + " " +count.ToString());
                    count = 0;
                }
            }
            
        }

One Answer

Instead of tracking the count, I'd track where the sequence starts instead:

int seqStartIndex = 0;

for (int i = 1; i < myList.Count; ++i)
{
    if (myList[i - 1] + 1 != myList[i])
    {
        Console.WriteLine($"number {myList[seqStartIndex]} sequence {i - seqStartIndex - 1}.");
        seqStartIndex = i;
    }
}

Answered by itsme86 on December 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP