在 n 个二维数组中搜索
你好 我需要在 n 个二维数组上实现以下逻辑。这里我考虑了 3 个一维数组
#include<stdio.h>
main()
{
int a[4]={2,1,4,7},b[4]={3,-3,-8,0},c[4]={-1,-4,-7,6},sum,i,j,k,val=0;
for(i=0;i<4;i++) {
for(j=0;j<4;j++) {
for(k=0;k<4;k++) {
sum = a[i]+b[j]+c[k];
if(sum == val)
printf("%d %d %d\n", a[i], b[j], c[k]);
}
}
}
}
输出: 2 -8 6 ; 1 3 -4 ; 1 0 -1 <强>; 4 3 -7 ; 4 -3 -1 <强>; 4 0 -4 <强>; 7 -3 -4 <强>; 7 0 -7 <强>;
Hi
I need the following logic to implement on an n arrays(of 2-dimensional) .Here I have considered 3 arrays of one dimensional
#include<stdio.h>
main()
{
int a[4]={2,1,4,7},b[4]={3,-3,-8,0},c[4]={-1,-4,-7,6},sum,i,j,k,val=0;
for(i=0;i<4;i++) {
for(j=0;j<4;j++) {
for(k=0;k<4;k++) {
sum = a[i]+b[j]+c[k];
if(sum == val)
printf("%d %d %d\n", a[i], b[j], c[k]);
}
}
}
}
Output:
2 -8 6 ;
1 3 -4 ;
1 0 -1 ;
4 3 -7 ;
4 -3 -1 ;
4 0 -4 ;
7 -3 -4 ;
7 0 -7 ;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有关语法信息,请参阅维基百科中的 C 语法。
实际上,您需要使用 int array[3][4] = ... 创建一个 3 行 4 列的数组。稍后在代码中,将对当前 a、b 和 c 数组的访问替换为每种情况的固定行索引。
其余的实现留作练习,因为这对我来说听起来像是家庭作业。
Please see C syntax in Wikipedia for syntax information.
In practice, you need to use int array[3][4] = ... to create an array with 3 rows and 4 columns. Later in code replace the accesses to current a, b and c arrays with a fixed row index for each case.
Rest of the implementation is left as an exercise as this sounds like homework to me.
好问题:-)
我不会发布完整的解决方案,因为问题似乎是家庭作业。只是一些提示......
我用递归解决了它:我使用的简化过程是在
n
数组中查找target
的总和与查找a相同n-1
数组中target - ONE_ELEMENT
的总和。使用 3 个数组和目标为零的示例
为了使其轻松工作,我创建了一个数据数组的结构,并提出一种在递归函数的多次调用之间传递信息的方法(我使用了在辅助递归设置函数中分配的另一个数组)。
编辑了数组的结构
以及递归和辅助函数的原型
以添加工作解决方案
Nice problem :-)
I will not post my full solution because the problem appears to be homework. Just a few pointers ...
I solved it with recursion: the simplification process I used was finding a sum of
target
inn
arrays is the same as finding a sum oftarget - ONE_ELEMENT
inn-1
arrays.Example using your 3 arrays and a target of zero
To make it work easily, I had create a data structure for the arrays and to come up with a way to pass information between the several invocations of the recursive function (I used another array allocated in the helper recursive setup function).
The structure for the arrays was
and the prototypes for the recursive and helper functions was
Edited to add a working solution