У меня есть следующий список:
List<int> Items = new List<int> { 0, 0, 1, 1, 0 }
Я хочу, чтобы одни и те же элементы в массиве, которые находятся рядом друг с другом, продолжали складываться до тех пор, пока следующий элемент в массиве не будет таким же, при этом вывод будет следующим:
0,2
1,2
0,1
Это код, который у меня есть:
public static void Test()
{
StringBuilder Data = new StringBuilder();
List<int> Items = new List<int> { 0, 0, 1, 1, 0 };
int Index = 1;
if (Items[0] != Items[1])
{
Data.AppendLine(Items[0] + " 1");
}
while (Index < Items.Count)
{
int PastValue = Items[Index - 1];
int CurrentValue = Items[Index];
int CurrentLength = 1;
while (CurrentValue == PastValue && Index + CurrentLength < Items.Count)
{
CurrentValue = Items[Index + CurrentLength];
CurrentLength += 1;
}
Data.AppendLine(CurrentValue + " " + CurrentLength);
Index = Index + CurrentLength;
}
Console.WriteLine(Data.ToString());
}
И выдает следующее, что неверно:
1,2
0,2
Есть ли лучший способ сделать это? Любая помощь очень ценится.
public static void Test()
{
StringBuilder Data = new StringBuilder();
List<int> Items = new List<int> { 0, 0, 1, 1, 0 };
int tempCount = 0;
int tempNumber = 0;
for ( int i = 0; i < Items.Count; i++ )
{
if ( Items[i].Equals(tempNumber) )
{
tempCount++;
}
else
{
if (tempCount>0)
{
Data.AppendLine( tempNumber + "," + tempCount );
}
tempNumber = Items[i];
tempCount = 1;
}
}
Data.AppendLine( tempNumber + "," + tempCount );
Console.WriteLine( Data.ToString() );
}
Это круто! Большое спасибо, все работает отлично. Я не знаю, почему кто-то проголосовал за это.
Начнем с этого метода расширения:
public static IEnumerable<(V Value, int Count)> Compress<V>(this IEnumerable<V> source)
{
var count = 0;
var current = default(V);
foreach (var value in source)
{
if (count == 0)
{
current = value;
count = 1;
}
else
{
if (current.Equals(value))
{
count++;
}
else
{
yield return (current, count);
current = value;
count = 1;
}
}
}
if (count != 0)
{
yield return (current, count);
}
}
Теперь я могу написать это:
List<int> Items = new List<int> { 0, 0, 1, 1, 0 };
List<(int Value, int Count)> output = Items.Compress().ToList();
Это дает мне:
Отобразить это становится легко:
string display = String.Join(Environment.NewLine, output.Select(o => $"{o.Value},{o.Count}"));
Console.WriteLine(display);
Это дает мне:
0,2
1,2
0,1
Еще один:
public static void Main(string[] args)
{
List<int> Items = new List<int> { 0, 0, 1, 1, 0 };
int count = 0;
int prevInt = 0;
List<Tuple<int, int>> results = new List<Tuple<int, int>>();
foreach(int i in Items)
{
if (count == 0 || i == prevInt)
{
count++;
}
else
{
results.Add(new Tuple<int, int>(prevInt, count));
count = 1;
}
prevInt = i;
}
if (count > 0)
{
results.Add(new Tuple<int, int>(prevInt, count));
}
String result = String.Join(Environment.NewLine, results);
Console.WriteLine(result);
Console.WriteLine("Press Enter to Quit.");
Console.ReadLine();
}
Вывод:
(0, 2)
(1, 2)
(0, 1)
Press Enter to Quit.
Подсказка: не занимайтесь строковой математикой. Выполните математику, используя целые числа, а затем создайте желаемый результат.