配列内のすべての繰り返し回数がminTimes以上の数値
3740 ワード
class Program
{
static void Main(string[] args)
{
int[] input = { 1, 1, 1, 2, 2, 5, 2, 4, 9, 9, 20 };
IDuplicationFinder dup1 = new Duplication1();
string str1 = dup1.FindDuplication(input, 3);
Console.WriteLine(str1);
IDuplicationFinder dup2 = new Duplication2();
string str2 = dup2.FindDuplication(input, 3);
Console.WriteLine(str2);
Console.Read();
}
}
class Duplication1 : IDuplicationFinder
{
public string FindDuplication(int[] input, uint minTimes)
{
Dictionary<int, int> valuedic = new Dictionary<int, int>();
#region
//foreach (var v in input)
//{
// var numtimes = input.Where(m => m == v).Count();
// if (numtimes >= minTimes && !valuedic.Keys.Contains(v))
// valuedic.Add(v, numtimes);
//}
#endregion
#region linq group
var groupnum = input.GroupBy(m => m);
foreach (var g in groupnum)
{
if (g.Count() >= minTimes)
valuedic.Add(g.Key, g.Count());
}
#endregion
return GetValue(valuedic);
}
private static string GetValue(Dictionary<int, int> valuedic)
{
StringBuilder sb = new StringBuilder();
foreach (var d in valuedic)
{
sb.AppendFormat("{0} {1} ", d.Key, d.Value);
sb.AppendLine();
}
return sb.ToString();
}
}
class Duplication2 : IDuplicationFinder
{
public string FindDuplication(int[] input, uint minTimes)
{
List<int> result = new List<int>();
Array.Sort(input);
if (minTimes == 1)// 1,
{
if (input[0] == input[1])
result.Add(input[1]);
for (int i = 1; i < input.Length - 1; i++)
{
if (input[i] != input[i + 1])
result.Add(input[i + 1]);
}
}
else
{
int count = 1;// , 1
for (int i = 0; i < input.Length - 1; i++)
{
if (result.Count > 0 && result.Last() == input[i])
continue;
if (input[i] == input[i + 1])
{
count++;
if (count >= minTimes)
{
result.Add(input[i]);
count = 1;
}
}
}
}
return string.Join(",", result);
}
}
interface IDuplicationFinder
{
string FindDuplication(int[] input, uint minTimes);
}
t=[1,22,33,1,44,22,11,3,224,5,6,22,1,44]// ruby
hst={}
t.each do |item|
if(hst.key?(item))
hst[item]+=1
else
hst[item]=1
end
end
p hst
b = Hash[hst.sort_by(){ |k, v| v }.reverse]
p b
p b.first