如何从数字数组中获取有关子序列的信息?
How to get information about subsequences from the 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};
对于上面的序列,我需要这样的东西:
"Group1" - [0, 0, 0, 0, 0]
"Group2" - [0, 0, 0]
"Group3" - [0, 0, 0, 0, 0, 0, 0, 0, 0, 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>();
}
}
您似乎在将连续的零分组。我会将您的结果存储在 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
我有一个数字数组 (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]
现在无法编译,但我猜……这样应该可以工作...
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>();
}
}
您似乎在将连续的零分组。我会将您的结果存储在 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