using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using UnityEngine;
namespace XGame
{
///
/// ALgorithm相关的实用函数。
///
public static partial class Utility
{
public static void Swap(ref T x, ref T y)
{
T t = x;
x = y;
y = t;
}
///
/// 递归求组合(从n个不同元素中取出m个元素组合)
///
///
/// 结果列表
/// 所求数组
/// 辅助变量
/// 辅助变量
/// 辅助下标存储数组
/// 辅助变量
public static void GetCombination(ref List list, T[] arr, int n, int m, int[] pos, int M)
{
for (int i = n; i >= m; i--)
{
pos[m - 1] = i - 1;
if (m > 1)
{
GetCombination(ref list, arr, i - 1, m - 1, pos, M);
}
else
{
T[] temp = new T[M];
for (int j = 0; j < M; j++)
{
temp[j] = arr[pos[j]];
}
if (list == null)
{
list = new List();
}
list.Add(temp);
}
}
}
///
/// 数组中n个元素的组合
///
///
/// 所求数组
/// 元素个数
/// 组合结果列表
public static List GetCombination(T[] arr, int n)
{
if (arr.Length < n)
{
return null;
}
List list = new List();
GetCombination(ref list, arr, arr.Length, n, new int[n], n);
return list;
}
///
/// 递归求排列(从n个不同元素中取出m个元素排列)
///
///
/// 结果列表
/// 所求数组
/// 起始标号
/// 结束标号
public static void GetPermutation(ref List list, T[] arr, int start, int end)
{
if (start == end)
{
T[] temp = new T[arr.Length];
arr.CopyTo(temp, 0);
if (list == null)
{
list = new List();
}
list.Add(temp);
}
for (int i = start; i <= end; i++)
{
Swap(ref arr[i], ref arr[start]);
GetPermutation(ref list, arr, start + 1, end);
Swap(ref arr[i], ref arr[start]);
}
}
///
/// 数组n个元素的排列
///
///
/// 所求数组
/// 元素个数
/// 排列结果列表
public static List GetPermutation(T[] arr, int n)
{
if (arr.Length < n)
{
return null;
}
List list = new List();
List comList = GetCombination(arr, n);
foreach (var com in comList)
{
List perList = new List();
GetPermutation(ref perList, com, 0, n - 1);
list.AddRange(perList);
}
return list;
}
}
}