1.使用方法:
string str = "abc";
Assemble assemble = new Assemble(str);
assemble.OnCreateOneGroup += (e) =>
{
Console.WriteLine(e);
};
assemble.DoRank();
2.封装类:
/// <summary>
/// 将给定的字符数组,进行排列,得到不同顺序的排列结果
/// </summary>
public class Assemble
{
/// <summary>
/// 需要排序的字符数组
/// </summary>
private char[] _Source = null;
/// <summary>
/// 排序结果字符串数组
/// </summary>
private List<string> _Result = null;
/// <summary>
/// 获取排序成功一个数组是触发
/// </summary>
public Action<string> OnCreateOneGroup = null;
/// <summary>
/// 初始化
/// </summary>
/// <param name="Source">需要排列的字符数组</param>
public Assemble(char[] Source)
{
if (Source == null || Source.Length <= 0)
throw new Exception("传入的字符数组,不能为空");
_Source = Source;
_Result = new List<string>();
}
/// <summary>
/// 初始化
/// </summary>
/// <param name="Source">需要排列的字符串</param>
public Assemble(string Source)
{
if (string.IsNullOrEmpty(Source))
throw new Exception("传入的字符串,不能为空");
_Source = Source.ToArray();
_Result = new List<string>();
}
/// <summary>
/// 执行排列
/// </summary>
public void DoRank()
{
Rank(_Source, 0, _Source.Length - 1);
}
/// <summary>
/// 排列方法
/// </summary>
/// <param name="source">源字符数组</param>
/// <param name="start">开始位置</param>
/// <param name="end">结束位置</param>
private void Rank(char[] source, int start, int end)
{
int i;
if (start > end)
{
StringBuilder builder = new StringBuilder(100);
for (i = 0; i <= end; i++)
{
builder.Append(source[i]);
}
string result = builder.ToString();
_Result.Add(result);
if (OnCreateOneGroup != null)
{
OnCreateOneGroup(result);
}
}
else
{
for (i = start; i <= end; i++)
{
Swap(ref source[start], ref source[i]);
Rank(source, start + 1, end);
//当一次排列结束,返回的时候再还原
Swap(ref source[start], ref source[i]);
}
}
}
/// <summary>
/// 交换字符位置
/// </summary>
private void Swap(ref char a, ref char b)
{
char temp = a;
a = b;
b = temp;
}
}