Ejercicio #7 Mi solucion recursiva no debe ser la mas optima. Pero he tenido que pensarla unos cuantos dias para hacerla. Asi que buena o mala aqui esta. El algoritmo recursivo para toda la cadena sale en 3 lineas pero para un numero espesifico de caracteres es un poco mas complicado. En este caso mi codigo les permite espesificar el numero de caracteres a combinar con todos los caracteres de un array de caracteres. El constructor te pide el archivo a crear o guardar el index, que son la cantidad de caracteres a combinar y finalmente un array de caracteres como referencia. Agradecimientos especiales al primo William UH, ya que sin el no hubiera esclarecido algunas dudas respecto a la combinatoria en general.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ECDundy.Programmer
{
class ECDundy_Combinatorial
{
static void Main(string[] args)
{
char[] arr = new char[26] { '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' };
Combinatorial p = new Combinatorial(@"c:\Combinations.txt", 4, arr);
p.Create();
}
}
class Combinatorial
{
private char[] Elements;
private string Result, FileName;
private List<string> _List;
private int Count,Index;
StreamWriter writer;
public Combinatorial(string FileName, int Index, params char[] Elements)
{
this.FileName = FileName;
this.Elements = Elements;
this.Index = Index;
writer = new StreamWriter(FileName);
Count=-1;
Result = "";
_List = new List<string>();
}
public void Create() { Combining_Characters(Elements, Result, _List, Index); writer.Close(); }
private void Combining_Characters(char[] Elements, string Result, List<string> _List, int Index)
{
char[] temp = new Char[Index];
string temp2 = "";
if (Result.Length == Elements.Length)
{
Count++;
for (int i = Elements.Length - 1, k = 0; i > (Elements.Length) - Index - 1; i--, k++)
{
temp[k] = Result;
}
temp2 = new string(temp);
if (!_List.Contains(temp2))
{
_List.Add(temp2);
Write_Text(temp2);
}
}
else
{
for (int i = 0; i < Elements.Length; i++)
{
if (Count == _List.Count) break;
else Combining_Characters(Elements, Result + Elements, _List, Index);
}
}
}
private void Write_Text(string str)
{
try
{
writer.WriteLine(str);
}
catch (Exception ex)
{
throw new Exception("Error" + ex);
}
}
}
}