這裏是我的C#類找到排列或組合:
public static class IEnumerableExtensions
{
public static IEnumerable<IEnumerable<T>> Arrange<T>(this IEnumerable<T> elements,
int places, bool allowRepeats = true, bool orderMatters = true)
{
return orderMatters ?
Permutate(elements, places, allowRepeats) :
Combine(elements, places, allowRepeats);
}
public static IEnumerable<IEnumerable<T>> Permutate<T>(this IEnumerable<T> elements, int places, bool allowRepeats = false)
{
foreach (var cur in elements)
{
if (places == 1) yield return cur.Yield();
else
{
var sub = allowRepeats ? elements : elements.Where(v => !v.Equals(cur));
foreach (var res in sub.Permutate(places - 1, allowRepeats))
{
yield return res.Prepend(cur);
}
}
}
}
public static IEnumerable<IEnumerable<T>> Combine<T>(this IEnumerable<T> elements, int places, bool allowRepeats = false)
{
int i = 0;
foreach (var cur in elements)
{
if (places == 1) yield return cur.Yield();
else
{
var sub = allowRepeats ? elements.Skip(i++) : elements.Skip(i++ + 1);
foreach (var res in sub.Combine(places - 1, allowRepeats))
{
yield return res.Prepend(cur);
}
}
}
}
public static IEnumerable<T> Yield<T>(this T item)
{
yield return item;
}
static IEnumerable<T> Prepend<T>(this IEnumerable<T> rest, T first)
{
yield return first;
foreach (var item in rest)
yield return item;
}
}
用法:
var places = new char[] { 'A', 'B', 'C' };
var routes = places.Permutate(3).ToArray();
//to remove reverse routes:
var noRev = (from r1 in routes
from r2 in routes
where r1.SequenceEqual(r2.Reverse())
select (r1.First() < r2.First() ? r1 : r2)).Distinct();
這是排列得,順便說一句。谷歌「得到列表的所有排列」,你會發現很多結果。 – Ryan 2012-01-10 04:26:38
還沒有找到答案,我已經搜索了互聯網,我的大學圖書館,並與我的大學的數學教授交談。 我沒有找到這個http://bytes.com/topic/c/answers/536779-richard-heathfields-tsp-permutation-algorithm 解釋如何找到所有排列,但我仍然試圖找到一種方法,只能得到顛倒後不一樣的排列。 – user802599 2012-02-13 04:21:01