读书人

C#数组元素如何判断重复

发布时间: 2012-05-15 14:35:29 作者: rapoo

C#数组元素怎么判断重复?
List<int> p2 = new List<int>(); // TODO: 初始化为适当的值
p2.Add(1);
p2.Add(2);
p2.Add(3);
p2.Add(4);
p2.Add(5);
p2.Add(6);
p2.Add(13);
p2.Add(12);
p2.Add(11);
p2.Add(12);
p2.Add(11);
p2.Add(12);

有一个这样的数组.然后想判断最后面的11.12 是否重复了三次.
xxxxxx 11.12 11.12 11.12 这样即为重复.
xxxxxx 13.12 11.12 11.12 这样就没达到重复.

////从后往前检测
////p1是元素段可以重复多少次.超过就为false.上面例子是三次.
////p3是元素段的长度.上面例子是2..两个元素为一组.
public static bool f6(List<int> p2, int p1,int p3)
{
/////我写了很久都不对.
}

求大神现身.

[解决办法]

C# code
protected internal void T(){    Dictionary<int, int> p2 = new Dictionary<int, int>();    Add(p2, 1);    Add(p2, 1);    Add(p2, 2);    Add(p2, 3);    Add(p2, 4);    Add(p2, 5);    Add(p2, 6);    Add(p2, 13);    Add(p2, 12);    Add(p2, 11);    Add(p2, 12);    Add(p2, 11);    Add(p2, 12);    Interaction.MsgBox("1出现3次了吗:" + Repeat3(p2, 1));    Interaction.MsgBox("12出现3次了吗:" + Repeat3(p2, 12));}protected internal bool Repeat3(Dictionary<int, int> dictionary, int number){    if (dictionary.ContainsKey(number)) {        return (dictionary[number] > 2);    } else {        return false;    }}protected internal void Add(Dictionary<int, int> dictionary, int number){    if (dictionary.ContainsKey(number)) {        dictionary[number] += 1;    } else {        dictionary[number] = 1;    }}
[解决办法]
C# code
var last6 = list.Skip(list.Count - 6).ToList();if (last.Select((x, i) => new { x, i }).All(x => (x.i % 2 == 0 || x.x == 12) && (x.i %2 == 1 || x.x == 11))){    ...}
[解决办法]
C# code
bool b=!p2.Where(p=>new int[]{11,12}.Contains(p)).GroupBy(p=>p).All(g=>g.Count()>=3);
[解决办法]
bool b=!p2.Where(p=>new int[]{11,12}.Contains(p)).GroupBy(p=>p).All(g=>g.Count()>=3);
[解决办法]
如果仅仅是判断,可以简单点,如下:
List<int> p2 = new List<int>(); // TODO: 初始化为适当的值
p2.Add(1);
p2.Add(2);
p2.Add(3);
p2.Add(4);
p2.Add(5);
p2.Add(6);
p2.Add(13);
p2.Add(12);
p2.Add(11);
p2.Add(12);
p2.Add(11);
p2.Add(12);
p2.Add(11);
p2.Add(12);
string str="";
foreach (int i in p2)
str += i.ToString();
if (Regex.IsMatch(str, @"(1112){3,}"))
MessageBox.Show("重复三次");
[解决办法]
原来我理解错了啊
[解决办法]
C# code
protected internal void S(){    List<int> p2 = new List<int>();    p2.Add(1);    p2.Add(2);    p2.Add(3);    p2.Add(4);    p2.Add(5);    p2.Add(6);    p2.Add(13);    p2.Add(12);    p2.Add(11);    p2.Add(12);    p2.Add(11);    p2.Add(12);    p2.Add(11);    p2.Add(12);    Interaction.MsgBox("[,11,,12,]:" + Repeat3(p2, ",11,,12,"));    Interaction.MsgBox("[,11,,3,]:" + Repeat3(p2, ",11,,3,"));}protected internal bool Repeat3(List<int> p2, string numbers){    StringBuilder value = new StringBuilder();    foreach (int p in p2) {        value.AppendFormat(",{0},", p);    }    return Regex.IsMatch(value.ToString(), string.Format("({0}){{3,}}", numbers), RegexOptions.IgnoreCase);} 


[解决办法]
思路类似:

http://blog.csdn.net/q107770540/article/details/6625243

读书人网 >C#

热点推荐