-4

我有一个数字数组(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};

对于上面的序列,我需要这样的东西:

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

2 回答 2

0

现在无法编译,但我猜…… 像这样应该工作......

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>();
    }
}
于 2015-06-22T20:04:10.370 回答
0

这看起来像您将连续的零放入组中。我会将你的结果存储在 a 中Dictionary<string, List<int>>,你必须知道当你找到一个零时你会创建一个新组,并且每个连续的零都将属于同一个组,直到序列被破坏。然后当找到下一个零时开始一个新组,依此类推。

就像是:

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])));

结果:

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
于 2015-06-22T20:44:11.663 回答