使用C#或F#查找包含单个字符的字符串排列

我想生成一个包含变量字符列表的字符串的所有可能排列的列表。 例如,如果我有字符串“ABC”,我希望有一个包含所有可能变体的列表,例如:A,B,C,AB,BC。

谢谢。

这是一个LINQ版本:

Func> perm = t => { Func> perm2 = null; perm2 = (t0, t1s) => from n in Enumerable.Range(0, t1s.Length) let c = t1s.Substring(n, 1) let x = t1s.Remove(n, 1) let h = t0 + c from r in (new [] { h, }).Concat(perm2(h, x)) select r; return perm2("", t); }; 

像这样用它:

 var ps = perm("abc"); 

它会执行一个懒惰的计算。

 var ps = perm("abcdefghijklmnopqrstuvwxyz").Take(2); // Only computes two values when executed 

很难准确地说出你想要什么,但根据你的例子输出,这里是我认为你在F#中做的事情。

 let combinations (s:string) = let rec loop acc i = seq { for i in i .. (s.Length - 1) do let acc = acc + s.[i..i] yield acc yield! loop acc (i + 1) } loop "" 0 combinations "ABC" |> Seq.toList //["A"; "AB"; "ABC"; "AC"; "B"; "BC"; "C"] 

这将返回给定一串字符的所有排列(不明显)。 它不是快速或有效的,但确实有效……

  public List permute(string value, string prefix = "") { List result = new List(); for (int x=0;x 

使用:

  List output = permute("abc"); 

看看F#Snippets上的这个片段

如果您正在寻找索引排列(而不是迭代所有排列),您可以使用名为factoradics( Source )的编号系统来查找它们。 这是原始文章中的代码,具有更强的C#样式(原始代码非常’C ++ ish’)和generics。

 ///  /// Permutes the specified atoms; in lexicographical order. ///  /// The type of elements. /// The atoms. /// The index of the permutation to find. /// The permutation. public static IList Permute(this IList atoms, int index) { var result = new T[atoms.Count]; Permute(atoms, result, index); return result; } ///  /// Permutes the specified atoms; in lexicographical order. ///  /// The type of elements. /// The atoms. /// The array to place the permutation in. /// The index of the permutation to find. public static void Permute(this IList atoms, IList target, int index) { if (atoms == null) throw new ArgumentNullException("atoms"); if (target == null) throw new ArgumentNullException("target"); if (target.Count < atoms.Count) throw new ArgumentOutOfRangeException("target"); if (index < 0) throw new ArgumentOutOfRangeException("index"); var order = atoms.Count; // Step #1 - Find factoradic of k var perm = new int[order]; for (var j = 1; j <= order; j++) { perm[order - j] = index % j; index /= j; } // Step #2 - Convert factoradic[] to numeric permuatation in perm[] var temp = new int[order]; for (var i = 0; i < order; i++) { temp[i] = perm[i] + 1; perm[i] = 0; } perm[order - 1] = 1; // right-most value is set to 1. for (var i = order - 2; i >= 0; i--) { perm[i] = temp[i]; for (var j = i + 1; j < order; j++) { if (perm[j] >= perm[i]) perm[j]++; } } // Step #3 - map numeric permutation to string permutation for (var i = 0; i < order; ++i) { target[i] = atoms[perm[i] - 1]; } }