在写一个远程的代码,如果本地有M个显示器,远程有N个显示器(M<=N),依据分辨率、显示器刷新频率等要求,需要对远程的N个显示器进行最佳分辨率修改,之后,需要从N个远程显示器中选择M个,跟本地显示器进行一对一的匹配。
即从 A(N, M) = N! / (N-M)! 种组合选择1种最优匹配,这里用到了排列组合,而 std::next_permutation()用于全排列A(N, N) = N!,用不了,只能自己写一个实现,一直不太擅长写这种逻辑的代码,花了大半天才写出来,也好在是写出来了,唉。
#include <vector>
#include <iostream>
int main()
{
const std::size_t select_count = 3;
const std::size_t element_count = 4;
std::vector<std::size_t> select_element_index_vector(select_count, 0);
std::vector<bool> select_element_mark_vector(element_count, false);
std::size_t select_index = 0;
std::size_t element_index = 0;
while (true)
{
if (select_index < select_count)
{
if (element_index < element_count)
{
if (select_element_mark_vector[element_index])
{
++element_index;
}
else
{
select_element_index_vector[select_index] = element_index;
select_element_mark_vector[element_index] = true;
++select_index;
++element_index;
if (select_count == select_index)
{
for (std::vector<std::size_t>::const_iterator iter = select_element_index_vector.begin(); select_element_index_vector.end() != iter; ++iter)
{
std::cout<< (*iter + 1) << " ";
}
std::cout << std::endl;
}
}
}
else
{
while (select_index > 0)
{
--select_index;
element_index = select_element_index_vector[select_index];
select_element_mark_vector[element_index] = false;
++element_index;
while (element_index < element_count && select_element_mark_vector[element_index])
{
++element_index;
}
if (element_index < element_count)
{
select_element_index_vector[select_index] = element_index;
select_element_mark_vector[element_index] = true;
++select_index;
element_index = 0;
break;
}
}
if (0 == select_index)
{
break;
}
}
}
else
{
--select_index;
select_element_mark_vector[select_element_index_vector[select_index]] = false;
}
}
return (0);
}
测试输出A(4, 3)
1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2