C# – Arrays
This is part the first C# problem, from arrays, given at Telerik C# 2 courses. Check it out.
The problem itself is put as comments in the first two lines. In general, one should write a simple console application, which reads a number and then generates and prints all permutations of the number.
If 3 is given, then all combinations of 1,2 and 3 are given. It is interesting to try with bigger numbers, but not with too big (up to 10), because the printing takes a long time 🙂
using System;
class AllPermutationsOfNNumbers
{
static void Main()
{
//reading the input data from the console
uint numberN;
do
{
Console.Write("Please enter the number N: ");
}
while (!uint.TryParse(Console.ReadLine(), out numberN));
if (numberN < 1)
{
Console.WriteLine("This combination is imposible");
}
else
{
// calculating the number of all combinations
for (uint i = 0; i < Math.Pow(numberN, numberN); i++)
{
uint conv = i;
uint[] arrayForPrint = new uint[numberN];
uint[] arrayForSort = new uint[numberN];
bool print = true;
//convert from decimal to n-number system
for (uint j = 0; j < numberN; j++)
{
arrayForPrint[numberN - j - 1] = conv % numberN;
arrayForSort[numberN - j - 1] = conv % numberN;
conv = conv / numberN;
}
//checking for the printing of the combination
Array.Sort(arrayForSort);
for (int j = 1; j < arrayForSort.Length; j++)
{
if (arrayForSort[j] == arrayForSort[j - 1])
{
print = false;
}
}
// print result
if (print)
{
Console.Write("{0}{1}", '{', arrayForPrint[0] + 1);
for (uint j = 1; j < numberN; j++)
{
Console.Write(", {0}", arrayForPrint[j] + 1);
}
Console.WriteLine("}");
}
}
}
}
}
The compiled code is here. Download it to check the performance.
The code of the current article is part of the free Bulgarian C# programming book.