求一函数(获取数组中指定重出现次数的元素集)
求一函数(获取数组中指定重出现次数的元素集)
如:a=1,2,2,3,3,4,4,4,5,5,5,6,6,6
指定取重复两次的元素:返回结果=2,3
[解决办法]
string[] arr=a.Split(',');
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (string i in arr)
{
if (dic.ContainsKey(i))
dic[i] = dic[i] + 1;
else
dic.Add(i, 1);
}
var query =
from a in arr
group arr by a into g
orderby g.Count()
select new
{
g.Key,
count = g.Count()
};
[解决办法]
Imports System.IO
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim arr As Integer() = {1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6}
Dim dict As Dictionary(Of Integer, Integer) = GetRepeat(arr, 2)
For Each key As Integer In dict.Keys
Console.WriteLine(key.ToString() + "重复了" + dict(key).ToString() + "次")
Next
Console.ReadKey()
End Sub
Function GetRepeat(ByVal arr As Integer(), ByVal repeat As Integer) As Dictionary(Of Integer, Integer)
Dim dict As New Dictionary(Of Integer, Integer)
For Each i As Integer In arr
If dict.ContainsKey(i) Then
dict(i) = dict(i) + 1
Else
dict.Add(i, 1)
End If
Next
Dim result As New List(Of Integer)
For Each key As Integer In dict.Keys
If dict(key) <> repeat Then result.Add(key)
Next
For Each key As Integer In result
dict.Remove(key)
Next
Return dict
End Function
End Module
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim arr As Integer() = {1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7}
Console.WriteLine(GetValue(arr, 2))
End Sub
Private Function GetValue(ByVal arr() As Integer, ByVal count As Integer) As String
Dim value As String = String.Empty
Dim dict As New Dictionary(Of Integer, Integer)
For Each i As Integer In arr
If dict.ContainsKey(i) Then
dict(i) = dict(i) + 1
Else
dict.Add(i, 1)
End If
Next
For Each key As Integer In dict.Keys
If dict(key) = count Then
value &= key & ","
End If
Next
Return value.Trim(",")
End Function