我在许多地方查找并试图了解如何通过递归获得任意数量的嵌套for循环。但我所理解的显然是错误的。
我需要在网格模式中生成n维空间中的坐标。实际问题具有不同范围的不同坐标,但为了首先得到更简单的东西,我在下面的代码中使用了相同的整数阶梯坐标范围。
#include <iostream>
using namespace std;
void recursion(int n);
int main(){
recursion(3);
return 0;
}
void recursion(int n)
{
if(n!=0){
for(int x=1; x<4; x++){
cout<<x<<" ";
recursion(n-1);
}
}
else cout<<endl;
}
我想,并期望输出为:
1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
1 3 1
1 3 2
1 3 3
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
2 3 1
2 3 2
2 3 3
3 1 1
3 1 2
3 1 3
3 2 1
3 2 2
3 2 3
3 3 1
3 3 2
3 3 3
相反,我得到的输出是
1 1 1
2
3
2 1
2
3
3 1
2
3
2 1 1
2
3
2 1
2
3
3 1
2
3
3 1 1
2
3
2 1
2
3
3 1
2
3
我无法弄清楚什么是错的。任何帮助找出错误或甚至其他方式来生成坐标将非常感激。谢谢!
答案 0 :(得分:3)
Non-recursive solution基于add-with-carry:
#include <iostream>
using namespace std;
bool addOne(int* indices, int n, int ceiling) {
for (int i = 0; i < n; ++i) {
if (++indices[i] <= ceiling) {
return true;
}
indices[i] = 1;
}
return false;
}
void printIndices(int* indices, int n) {
for (int i = n-1; i >= 0; --i) {
cout << indices[i] << ' ';
}
cout << '\n';
}
int main() {
int indices[3];
for (int i=0; i < 3; ++i) {
indices[i] = 1;
}
do {
printIndices(indices, 3);
} while (addOne(indices, 3, 3));
return 0;
}
Recursive solution,从原始代码中抢救出来:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void recursion(int n, const string& prefix);
int main(){
recursion(3, "");
return 0;
}
void recursion(int n, const string& prefix)
{
if (n!=0) {
for(int x=1; x<4; x++){
ostringstream os;
os << prefix << x << ' ';
recursion(n-1, os.str());
}
}
else cout << prefix << endl;
}
答案 1 :(得分:0)
根据Igor的评论,你需要一个增量函数。
我们使用std::vector
来表示每个维度。即vector [0]是第一维,vector [1]是第二维,依此类推。
使用矢量允许我们确定没有任何硬编码数字的维数。 vector.size()将是维数。
这是一个让你入门的功能:
void Increment_Coordinate(std::vector<int>& coordinates,
int max_digit_value,
int min_digit_value)
{
unsigned int digit_index = 0;
bool apply_carry = false;
do
{
apply_carry = false;
coordinates[digit_index]++; // Increment the value in a dimension.
if (coordinates[digit_index] > max_digit_value)
{
// Reset the present dimension value
coordinates[digit_index] = min_digit_value;
// Apply carry to next column by moving to the next dimension.
++digit_index;
apply_carry = true;
}
} while (apply_carry);
return;
}
修改1 这只是一个基础。该功能需要进行边界检查 此功能不支持不同尺寸的尺寸。这是留给读者或OP的练习。
答案 2 :(得分:-1)
#include <bits/stdc++.h>
using namespace std;
void print(int *a,int n)
{
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<"\n";
}
void perm(int *a,int n,int k,int l)
{
if(l==k)
{
print(a,n);
}
else
{
for(int i=1;i<=n;i++)
{
a[l]=i;
perm(a,n,k,l+1);
}
}
}
int main()
{
int n,k,*a,l=0;
cout<<"enter the upper bound of numbers to work upon"<<"\n";
cin>>n;
cout<<"enter the number of places"<<"\n";
cin>>k;
a=new int[k];
perm(a,n,k,l);
return 0;
}