i tried to make a program that finds the maximal sequence of equal elements in an array. for example:
input: 2, 1, 1, 2, 3, 3, 2, 2, 2, 1
result: 2, 2, 2
using System;
using System.Collections.Generic;
class MaximalSequence
{
static void Main()
{
string[] array = Console.ReadLine().Split(new[] { ", " }, StringSplitOptions.None);
string previous = string.Empty;
List<string> sequence = new List<string>();
List<string> tempSequence = new List<string>();
for (int i = 0; i < array.Length; i++)
{
if (array[i] != previous)
{
tempSequence.Add(previous);
if (tempSequence.Count > sequence.Count)
{
sequence = tempSequence;
}
tempSequence.Clear();
}
else
{
tempSequence.Add(previous);
}
previous = array[i];
}
Console.WriteLine(string.Join(", ", sequence));
}
}
the problem is that for some reason on tempSequence.Clear();
both lists are cleared.
Like others have pointed out, List
is a reference type so assignment assigns by reference. This means that both variable are changing the same underlying object (so the .Clear
clears both lists).
The solution is to make a separate object with the same contents (aka a deep copy). List
provides a constructor public List(IEnumerable<T> collection)
that copies elements from another collection (List
).
In your code, replace sequence = tempSequence;
with
sequence = new List<string>(tempSequence);
See this .NET Fiddle