using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MathDemo
{
class Program
{
static void Main(string[] args)
{
//取1-1000的素数和。素数只能被1和本身相除。
/*
const int number = 1000;
int count = 0;
for (int i = 1; i < number; i++)
{
int k = 0;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
k++;
break;
}
}
if (k == 0)
{
count += i;
}
}
Console.WriteLine(count);
Console.ReadLine();
*/
//对一个不规则的整数数组排列,第n个元素和后续的元素相比,元素换位。
//int[] a = { 5, 2, 7, 9, 1 };
//for (int i = 0; i < a.Length; i++)
//{
// for (int j = i+1; j<a.Length; j++)
// {
// if (a[i] > a[j])
// {
// int temp = a[i];
// a[i] = a[j];
// a[j] = temp;
// }
// }
// Console.WriteLine(a[i]);
//}
//Console.ReadLine();
//全排列
char[] array = ("ABCDEF").ToCharArray();
List<string> lists = new List<string>();
AppendNextElement(array,lists,1);
if (lists.Count > 0)
{
for (int i = 0; i < lists.Count; i++)
{
Console.WriteLine(lists[i]);
}
Console.ReadLine();
}
}
public static void AppendNextElement(char[] element, List<string> lists,int AppendTime)
{
//把所有的char 数组中的元素全放入list,第一次附加
if (AppendTime == 1)
{
for (int i = 0; i < element.Length; i++)
{
if (!lists.Contains(element[i].ToString()))
{
lists.Add(element[i].ToString());
}
}
}
//第1次以后,所有的元素都又会循环附加char数组的元素,但是如果已有list元素中含有即将被附加进来的元素,则不附加,例如("AA","ABA","ACBC")
else
{
//循环次数已现在有的长度为准
int length = lists.Count;
for (int j = 0; j < length; j++)
{
for (int k = 0; k < element.Length; k++)
{
if (lists[j].Length == 1)
{
if (lists[j] != element[k].ToString())
{
string temp = lists[j] + element[k].ToString();
lists.Add(temp);
}
}
else
{
//判断最后一个元素是不是和要附加的元素是否相等,相等则不附加
if (lists[j].Substring(lists[j].Length - 1) != element[k].ToString())
{
//判断列表中的元素是否包含要附加的元素,有则不附加
if (!lists[j].Contains(element[k].ToString()))
{
string temp = lists[j] + element[k].ToString();
lists.Add(temp);
}
}
}
}
}
//附加完后考虑到前面生成的元素没有被删除,删除前面的元素。比如数组char A,B
//第2次附加完后应该是A,B,AB,BA,则删除元素A和B,数量是数学公式排列p2,1
//数组Char A,B,C
//第2次附加完后应该是A,B,C,AB,AC,BA,BC,CA,CB则删除元素A,B和C
//第3次附加完后应该删除AB,AC,BA,BC,CA,CB
if (AppendTime > 1)
{
lists.RemoveRange(0, getjiechen(element.Length,AppendTime-1));
}
}
//第1次 附加AppendTime = 1
//第2次 附加AppendTime = 2
//....... 3
//....... 4
//....... .
AppendTime++;
if (AppendTime <= element.Length)
{
AppendNextElement(element, lists, AppendTime);
}
return;
}
//根据char 数组的长度和第几次附加,取得对应的阶乘
public static int getjiechen(int length,int count)
{
int total = 1;
for (int i = 0; i < count; i++)
{
total *= length;
length--;
}
return total;
}
}
}