【欢迎挑战】两个数组交叉排列算法,本组元素不相邻
本帖最后由 u011457062 于 2013-07-19 22:18:47 编辑 string[] en = { "A", "B", "C" };
string[] num = { "1", "2", "3" };
两个数组交叉排列组合,字母和字母隔开,数字和数字不相邻,有多少种排法? 请用编程输出所有结果
输出结果示例:
A 1 B 2 C 3
A 1 B 3 C 2
A 2 B 1 C 3
A 2 B 3 C 1
A 3 B 1 C 2
A 3 B 2 C 1
A 1 C 2 B 3
A 1 C 3 B 2
A 2 C 1 B 3
A 2 C 3 B 1
A 3 C 1 B 2
A 3 C 2 B 1
B 1 A 2 C 3
B 1 A 3 C 2
B 2 A 1 C 3
B 2 A 3 C 1
B 3 A 1 C 2
B 3 A 2 C 1
B 1 C 2 A 3
B 1 C 3 A 2
B 2 C 1 A 3
B 2 C 3 A 1
B 3 C 1 A 2
B 3 C 2 A 1
...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] en = { "A", "B", "C" };
string[] num = { "1", "2", "3" };
var result = Arrange(en).SelectMany(x => Arrange(num).Select(y => new { x, y }))
.Select(x => string.Join(" ", x.x.Zip(x.y, (a, b) => a + b).ToArray()));
foreach (string item in result)
{
Console.WriteLine(item);
}
}
static IEnumerable<IEnumerable<T>> Arrange<T>(IEnumerable<T> data) where T : IComparable
{
var query = data.Select(x => new List<T>() { x });
for (int i = 0; i < data.Count() - 1; i++ )
{
query = query.SelectMany(x => data.Where(y => !x.Contains(y)).Select(y => x.Concat(new List<T>() { y }).ToList()));
}
return query;
}
}
}
B3 C2 A1
C1 A2 B3
C1 A3 B2
C2 A1 B3
C2 A3 B1
C3 A1 B2
C3 A2 B1
C1 B2 A3
C1 B3 A2
C2 B1 A3
C2 B3 A1
C3 B1 A2
C3 B2 A1
Press any key to continue . . .
[解决办法]
2*3!*3! =72种。
#include <iostream>
#include <list>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string en="ABC";
string num="123";
list<string> num_perm;
do{
num_perm.push_back(num);
}while(next_permutation(num.begin(), num.end()));
do{
for(auto i:num_perm) {
for(int j=0;j<en.size();++j)
cout<<en[j]<<i[j]<<" ";
cout<<endl;
}
}while (next_permutation(en.begin(), en.end()));
return 0;
}