How to get information about subsequences from the array of numbers?

176 views Asked by At

I have an array of numbers (C#):

int[] seq = new[] { 2, 1, 4, 2, 1, 3, 
0, 0, 0, 0, 0, 
1, 5, 2, 3, 7, 
0, 0, 0, 
1, 2, 3, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

For the sequence above I need something like this:

"Group1" - [0, 0, 0, 0, 0]
"Group2" - [0, 0, 0]
"Group3" - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
2

There are 2 answers

0
Shar1er80 On BEST ANSWER

This looks like you're putting consecutive zeros into groups. I would store your results in a Dictionary<string, List<int>> and you'll have to know when you find a zero you create a new group and every consecutive zero will belong to the same group until the sequence is broken. Then a new group is started when the next zero is found, and so on.

Something like:

int[] seq = new[] { 
    2, 1, 4, 2, 1, 3, 
    0, 0, 0, 0, 0, 
    1, 5, 2, 3, 7, 
    0, 0, 0, 
    1, 2, 3, 
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

bool newGroup = false;
Dictionary<string, List<int>> groups = new Dictionary<string, List<int>>();
foreach (int t in seq)
{
    if (t == 0)
    {
        if (!newGroup)
        {
            groups.Add(String.Format("Group{0}", groups.Count + 1), new List<int>());
            newGroup = true;
        }
        groups[groups.Keys.Last()].Add(t);
    }
    else
    {
        newGroup = false;
    }
}

groups.Keys.ToList().ForEach(k => Console.WriteLine("Key {0}: Value: {1}", k, String.Join(", ", groups[k])));

Results:

Key Group1: Value: 0, 0, 0, 0, 0
Key Group2: Value: 0, 0, 0
Key Group3: Value: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0
nozzleman On

Cant compile right now, but i guess sth. like this should work...

var prev = seq[0];
var subseq = new List<int> { prev };

var retVal = new List<List<int>>();

for (var i = 1; i < seq.Length; i++)
{
    if (seq[i] == prev)
    {
        subseq.Add(seq[i]);
    }
    else
    {
        if (subseq.Count() > 1) 
        {
            retVal.Add(subseq);
        }

        subseq = new List<int>();
    }
}