Разбор программы с листами - C#
Формулировка задачи:
Console.Write("ввод длины k:");
int k = Convert.ToInt32(Console.ReadLine());
Console.Write("состоит из чисел от 1 до:");
int n = Convert.ToInt32(Console.ReadLine());
Queue<List<int>> q = new Queue<List<int>>();
q.Enqueue(new List<int>(k));
while (q.Count != 0)
{
List<int> prev = q.Dequeue();
if (prev.Count == k)
{
Console.WriteLine(String.Join(String.Empty, prev.Select(i => i.ToString())));
}
else
{
for (int i = prev.LastOrDefault() + 1; i <= n; i++)
{
List<int> next = new List<int>(prev);
next.Add(i);
q.Enqueue(next);
}
}
}Решение задачи: «Разбор программы с листами»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Print(IEnumerable<int> elems)
{
Console.WriteLine("{{{0}}}", elems.Aggregate("", (s, e) => s + e));
}
static void Main(string[] args)
{
Console.Write("ввод длины k:");
int k = Convert.ToInt32(Console.ReadLine());
Console.Write("состоит из чисел от 1 до:");
int n = Convert.ToInt32(Console.ReadLine());
Queue<List<int>> q = new Queue<List<int>>();
q.Enqueue(new List<int>(k));
Console.Write("Добавлено: ");
Print(new int[] { });
Console.WriteLine();
while (q.Count != 0)
{
List<int> prev = q.Dequeue();
Console.Write("Извлечено: ");
Print(prev);
Console.WriteLine();
if (prev.Count == k)
{
Console.WriteLine(String.Join(String.Empty, prev.Select(i => i.ToString())));
}
else
{
for (int i = prev.LastOrDefault() + 1; i <= n; i++)
{
List<int> next = new List<int>(prev);
next.Add(i);
Console.Write("Добавлено: ");
Print(next);
q.Enqueue(next);
}
Console.WriteLine();
}
}
}
}