Найти и определить последовательности в массиве данных
class Program
{
internal static void Calculate(int[] arr)
{
List<string> combinations = new List<string>();
int countofcombinations = 1;
string tempstr = "";
for (int i = 1; i < arr.Length; i++)
{
if (arr[i - 1] < arr[i] && arr[i - 1] != arr[i])
{
tempstr += arr[i - 1].ToString() + ",";
}
else if (arr[i - 1] != arr[i])
{
combinations.Add(tempstr);
tempstr = "";
countofcombinations++;
}
}
Console.WriteLine("Input data: " + String.Join(",", arr));
Console.WriteLine("Count of combinations: " + countofcombinations);
Console.WriteLine("Combinations: " + String.Join(" | ", combinations));
Console.ReadLine();
}
static void Main(string[] args)
{
Calculate(new int[] { 1, 2, 3, 75, 4, 5, 6, 75, 7, 8, 9, 108, 1,2,3, 875 });
}
}
Выводит:
Input data: 1,2,3,75,4,5,6,75,7,8,9,108,1,2,3,875
Count of combinations: 4
Combinations: 1,2,3, | 4,5,6, | 7,8,9, @(1,2,3)" - теряется
Но почему-то не выводит последнюю последовательность. В чём ошибка?
Ответы (2 шт):
Автор решения: CrazyElf
→ Ссылка
После окончания цикла for в tempstr теоретически может остаться (и точно остаётся в вашем случае) не обработанная строка. Нужно её обработать:
for (int i = 1; i < arr.Length; i++)
{
// ...
}
if (tempstr.Length > 0)
{
combinations.Add(tempstr);
countofcombinations++;
}
Автор решения: KuzCode
→ Ссылка
Вам уже ответили, почему метод не работает так как вы ожидаете.
Я же хочу показать пример хорошего кода:
public class Program
{
public static List<List<int>> FindCombinations(int[] array)
{
if (array == null)
throw new ArgumentNullException();
var combinations = new List<List<int>>() { new List<int>() };
for (int i = 0; i < array.Length - 1; i++)
{
if (array[i] > array[i + 1])
{
combinations.Add(new List<int>());
continue;
}
combinations.Last().Add(array[i]);
}
return combinations;
}
public static void Main()
{
var inputArray = new int[] { 1, 2, 3, 75, 4, 5, 6, 75, 7, 8, 9, 108, 1, 2, 3, 875 };
var combinations = FindCombinations(inputArray);
Console.WriteLine("Input data: " + string.Join(", ", inputArray));
Console.WriteLine("Count of combinations: " + combinations.Count);
Console.WriteLine("Combinations:");
combinations.ForEach(combination => Console.WriteLine(string.Join(", ", combination)));
}
}
Вывод:
Input data: 1, 2, 3, 75, 4, 5, 6, 75, 7, 8, 9, 108, 1, 2, 3, 875
Count of combinations: 4
Combinations:
1, 2, 3
4, 5, 6
7, 8, 9
1, 2, 3