I'm very new to programming, and my good friend is given me some "assignments" that I can solve.
He recently asked me to write a program (console app) that will write all the permutations of the first N letters of the alphabeth. So if N = 3, it will write:
ABC ACB BAC BCA CAB CBA
I've learned about recursive functions, arrays and lists. This is what I got so far, I made it from several answers here from stackoverflow, all I need to learn is how I can make it write only the first N letters out:
class Program
{
static void Main()
{
string[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
foreach (string[] permutation in Permutation.GetPermutations<string>(items))
{
Console.WriteLine(String.Join(", ", permutation));
}
Console.ReadKey();
}
}
public class Permutation
{
public static IEnumerable<T[]> GetPermutations<T>(T[] items)
{
int[] work = new int[items.Length];
for (int i = 0; i < work.Length; i++)
{
work[i] = i;
}
foreach (int[] index in GetIntPermutations(work, 0, work.Length))
{
T[] result = new T[index.Length];
for (int i = 0; i < index.Length; i++) result[i] = items[index[i]];
yield return result;
}
}
public static IEnumerable<int[]> GetIntPermutations(int[] index, int offset, int len)
{
if (len == 1)
{
yield return index;
}
else if (len == 2)
{
yield return index;
Swap(index, offset, offset + 1);
yield return index;
Swap(index, offset, offset + 1);
}
else
{
foreach (int[] result in GetIntPermutations(index, offset + 1, len - 1))
{
yield return result;
}
for (int i = 1; i < len; i++)
{
Swap(index, offset, offset + i);
foreach (int[] result in GetIntPermutations(index, offset + 1, len - 1))
{
yield return result;
}
Swap(index, offset, offset + i);
}
}
}
private static void Swap(int[] index, int offset1, int offset2)
{
int temp = index[offset1];
index[offset1] = index[offset2];
index[offset2] = temp;
}
}
string[] validLetters = items.Take(n).ToArray();Nvalue to yourGetPermutations<T>()method and initializeworkasnew int[n]instead ofnew int[items.Length]. Or any number of other ways.