gpt4 book ai didi

c++ - 找到所有可能的大小为 n 的数组,这些数组是用另一个数组中所有可能的顺序的元素的所有可能组合构造的?

转载 作者:行者123 更新时间:2023-11-30 17:44:45 29 4
gpt4 key购买 nike

对于任意长度 n 的数组 A,我想用 A 中元素的所有组合填充 n x m 数组 B,其中包括这些元素的所有可能顺序。例如,如果 A = {1, 2, 3} 且 m = 2,我希望 B 为:

11

12

13

21

22

23

31

32

33

在 C/C++ 中执行此操作的有效方法是什么?谢谢!

编辑:这是我想出的工作方式(数据位于类梳内,它基本上是一个带有一些附加技巧的矩阵类):

void combs::setCombs (int arr[], int n, int m) {
int z, tmp, repeat;
int max = (int (pow(double (n), double( m ))));
for (int i = 0; i < m; i++) {
z = 0;
repeat = int (pow( double (n), double (i)));
for (int j = 0; j < repeat; j++) {
for (int k = 0; k < n; k ++) {
for (int p = 0; p < max/(n*repeat); p ++) {
cout << arr[k] << endl;
data[z*ROWS + i] = arr[k];
z++;
}
}
}
}
}

最佳答案

正如@Joachim Pileborg 所提到的,你的问题在参数方面缺乏很多。
但是可以说你可以保证你向我传递了一个已排序的唯一整数的 vector 。那么这种蛮力是可能的:

std::vector< std::string > Combo( const std::vector< char >& source, int m )
{
std::vector< std::vector< char >::const_iterator > digits( length, source.cbegin() );
std::vector< std::string > result( source.size() * m );

for( int i = 0; i < result.size(); i++ )
{

for( int j = 0; j < m; j++ )
{
result[i] += *(digits[j]);
}

for( int j = digits.size() - 1; j >= 0; j-- )
{
++digits[j];

if( digits[j] == source.cend() )
{
digits[j] = source.cbegin();
}
else
{
break;
}
}
}
return result;
}

关于c++ - 找到所有可能的大小为 n 的数组,这些数组是用另一个数组中所有可能的顺序的元素的所有可能组合构造的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19868013/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com