Для упрощения, а не для разбора строк и сравнения дат.
Для того, чтобы иметь ясные mre , DateTime
теперь int
.
Live demo
Контрольный пример.
Основываясь на вопросе, у меня есть следующий контрольный пример:
//Input Expected Output
{ null, 1 }, { null, 1 }
{ null, null, 1 }, { null, null, 1 }
{ null, null , null, 1 }, { null, null , null, 1 }
{ 1, null, 1 }, { 1, 1, 1 }
{ 1, null, null, 1 }, { 1, 1, 1, 1 }
{ 1, null, null, null, 1 }, { 1, null, null, null, 1 }
{ 1, null, 2 }, { 1, null, 2 }
{ 1, null, null, 2 }, { 1, null, null, 2 }
{ 1, null, null, null, 2 }, { 1, null, null, null, 2 }
Код.
Здесь мы выигралине ищите оптимизации кода, минимального назначения переменных или сохранения последнего значения, которое мы только что прочитали. Мы остаемся рядом с тестовым набором.
for (int i = 0; i < input.Length - 1; i++)
{
if (i == 0) { continue; } //First elment? Skip.
if (input[i] != null) { continue; }// Already have a value? Skip.
// First and last elment are safe.
int? closestValueLeft = input[i - 1];
int? closestValueRight = input[i + 1];
// #### CASE 1 #### : Left and right have value.
if (closestValueLeft != null && closestValueRight != null)
{
if (closestValueLeft == closestValueRight)
{// both are the same.
input[i] = closestValueLeft;
}
}
// #### CASE 2 #### : Left and right don't have value.
else if (closestValueLeft == null && closestValueRight == null)
{// Left and right have no value, Skip.
continue;
}
// #### CASE 3 #### : We have to move a bit to find
else
{// Either left or right have a value but not both. We are gona move one step after the null.
if (closestValueLeft != null)
{ // Left is not null move right.
if (i + 2 < input.Length)// Array out of bound protection
{
closestValueRight = input[i + 2];
}
}
else
{// Right is not null, move left.
if (i - 2 > 0)// Array out of bound protection
{
closestValueLeft = input[i - 2];
}
}
if (closestValueLeft == closestValueRight)
{
input[i] = closestValueLeft;
}
}
}