我有星辰,太阳,月亮(例如)
我有以下清单:
STAR,
SUN,
SUN,
SUN,
SUN,
SUN,
MOON,
STAR,
STAR,
STAR,
STAR,
STAR,
STAR,
STAR,
STAR,
STAR,
STAR,
STAR,
STAR,
MOON我正在寻找一种制作以下清单的方法:
STAR,
SUN,
MOON,
STAR,
STAR,
MOON如果我们有来自同一类型的1-5元素,我们添加了1项,如果我们有超过5,我们添加了数字/5或6,如果我们有15个月亮,我们在新列表中添加3,如果我们有22,我们添加4,如果我们有30,我们添加5等等。
发布于 2016-12-04 13:30:00
2个实现,选择您喜欢的一个。
第一(从原始列表中删除项目):
// usage:
MyFilter(list);
// method:
static void MyFilter(List<MyEnum> list)
{
int repetitions = 1;
MyEnum repeatValue = list[0];
int i = 1;
while(i < list.Count) {
MyEnum current = list[i];
if(current == repeatValue) {
repetitions++;
if(repetitions>9 && repetitions%5==0)
i++;
else
list.RemoveAt(i);
} else {
repetitions=1;
repeatValue=current;
i++;
}
}
}第二(构建一个新列表):
// usage:
list = MyFilter(list);
// method:
static List<MyEnum> MyFilter(List<MyEnum> list)
{
List<MyEnum> result = new List<MyEnum>();
int repetitions = 0;
MyEnum? repeatValue = null;
for(int i=0; i<=list.Count; i++) {
MyEnum? current = null;
if(i < list.Count) {
current = list[i];
if(repeatValue==null || current==repeatValue) {
repetitions++;
repeatValue=current;
continue;
}
}
if(repetitions <= 5) {
result.Add(repeatValue.Value);
} else {
for(int j=repetitions/5; j>0; j--)
result.Add(repeatValue.Value);
}
repetitions = 1;
repeatValue = current;
}
return result;
}发布于 2016-12-04 13:35:06
您需要在找到第一项时输出值,跳过2到5项。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] input = { "STAR",
"SUN",
"SUN",
"SUN",
"SUN",
"SUN",
"MOON",
"STAR",
"STAR",
"STAR",
"STAR",
"STAR",
"STAR",
"STAR",
"STAR",
"STAR",
"STAR",
"STAR",
"STAR",
"MOON"
};
Dictionary<string, int> dict = new Dictionary<string, int>();
List<string> output = new List<string>();
foreach (string str in input)
{
if (dict.ContainsKey(str))
{
int count = dict[str];
if ((count % 5) == 0)
{
output.Add(str);
}
dict[str] += 1;
}
else
{
dict.Add(str, 0);
}
}
}
}
}https://stackoverflow.com/questions/40958932
复制相似问题