using System;
namespace Permutations
{
/// <summary>
/// Permutations in C# Using Recursion:
/// Caluclate permutations of a set of elements using a simple recursive algorithm
/// </summary>
class Program
{
static void Main(string[] args)
{
Console.Write("Input Letters>");
string inputLine = Console.ReadLine();
Algorithms permAlgorithm = new Algorithms();
permAlgorithm.InputSet = permAlgorithm.MakeCharArray(inputLine);
permAlgorithm.Recursion(0);
Console.Write("# of Permutations: " + permAlgorithm.PermutationCount);
}
}
class Algorithms
{
private int elementLevel = -1;
private int numberOfElements;
private int[] permutationValue = new int[0];
private char[] inputSet;
public char[] InputSet
{
get { return inputSet; }
set { inputSet = value; }
}
private int permutationCount = 0;
public int PermutationCount
{
get { return permutationCount; }
set { permutationCount = value; }
}
public char[] MakeCharArray(string InputString)
{
char[] charString = InputString.ToCharArray();
Array.Resize(ref permutationValue, charString.Length);
numberOfElements = charString.Length;
return charString;
}
/// <summary>
/// Recursive Algorithm Source:
/// A. Bogomolny, Counting And Listing All Permutations from Interactive Mathematics Miscellany and Puzzles
///
http://www.cut-the-knot.org/do_you_know/AllPerm.shtml, Accessed 11 June 2009
/// </summary>
/// <param name="k"></param>
public void Recursion(int k)
{
elementLevel++;
permutationValue.SetValue(elementLevel, k);
if (elementLevel == numberOfElements)
{
OutputPermutation(permutationValue);
}
else
{
for (int i = 0; i < numberOfElements; i++)
{
if (permutationValue[i] == 0)
{
Recursion(i);
}
}
}
elementLevel--;
permutationValue.SetValue(0, k);
}
/// <summary>
/// Code Source (AddItem()):
/// A. Bogomolny, Counting And Listing All Permutations from Interactive Mathematics Miscellany and Puzzles
///
http://www.cut-the-knot.org/do_you_know/AllPerm.shtml, Accessed 11 June 2009
/// </summary>
/// <param name="value"></param>
private void OutputPermutation(int[] value)
{
foreach (int i in value)
{
Console.Write(inputSet.GetValue(i - 1));
}
Console.WriteLine();
PermutationCount++;
}
}
}
Are there any errors in this?
It closes automatically after exucation. How can i make it to stay there?