Все возможные комбинации чисел - C#
Формулировка задачи:
Есть числа 1,2,3,7,8,9.
Как вывести их все возможные комбинации, если известно что цифры не могут повторяться? Нужно в консоли
Как-то так:
123897
213789
...
398271
Решение задачи: «Все возможные комбинации чисел»
textual
Листинг программы
using System;
namespace ConsoleApplication
{
public class Permutations<T>
{
public static System.Collections.Generic.IEnumerable<T[]> AllFor(T[] array)
{
if (array == null || array.Length == 0)
{
yield return new T[0];
}
else
{
for (int pick = 0; pick < array.Length; ++pick)
{
T item = array[pick];
int i = -1;
T[] rest = System.Array.FindAll<T>(
array, delegate(T p) { return ++i != pick; }
);
foreach (T[] restPermuted in AllFor(rest))
{
i = -1;
yield return System.Array.ConvertAll<T, T>(
array,
delegate(T p)
{
return ++i == 0 ? item : restPermuted[i - 1];
}
);
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
int[] nums = { 1, 2, 3, 7, 8, 9 };
foreach (int[] permutation in Permutations<int>.AllFor(nums))
{
Console.WriteLine(string.Join(" ", permutation));
}
Console.ReadKey();
}
}
}