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 🙂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
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.