大佬教程收集整理的这篇文章主要介绍了排列和二维数组,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想检查三个具有相同维度的矩阵 A、B、C 是否是彼此的排列(在每个二维数组中包含具有相同重复次数的相同元素),如果是则返回 1,如果不是则返回 0 .我的代码不能正常工作;在这种情况下,它返回 1 1 1 1 而不是 1 0 1 0。我希望你能帮助我。
#include <stdio.h>
#define MAX 100
int permutation (double A[100][100],double B[100][100],double C[100][100],int M,int n){
int i,j,x,y,true;
for(i=0;i<M;i++)
for(j=0;j<N;j++){
true=1;
for(x=0;x<M-i && true;x++)
for(y=0;y<N-j && true;y++)
if(A[i+x][j+y]!=B[i+x][j+y] || A[i+x][j+y]!=C[i+x][j+y])
true=0;
if(true) return 1;
}
return 0;
}
int main(){
double A[100][100] = { {1,2,3},{4,5,6},{7,8,9} };
double B[100][100] = { {4,1,9},{6,5} };
double C[100][100] = { {8,4,{5,1},9,3} };
printf("%d ",permutation(A,B,C,3,3) );
C[2][2] = 1;
printf("%d ",3) );
C[1][2] = 3;
printf("%d ",3) );
B[2][2] = 10;
printf("%d ",3) );
}
我已经编辑了它以删除我对这个特定示例有效的第一次尝试,但通常不起作用(如评论中所指出的,谢谢)。我会留下我的第二个选择。
我的首选解决方案与您目前正在做的完全不同,因此它可能不是您想要的,但总的来说,我喜欢简单排序和直接比较的想法。
// A comparison function to work with qsort from stdlib.h
// Like the original code,this checks for actual inequality,but when dealing with doubles you might want to look into using DBL_EPSILON from float.h
int doublecomp(const void *v1,const void *v2) {
double d1 = *(double *)v1;
double d2 = *(double *)v2;
if (d1 > d2) {
return 1;
}
if (d1 < d2) {
return -1;
}
return 0;
}
int permutation (double A[100][100],double B[100][100],double C[100][100],int M,int n) {
double ap[M*N]; // Assuming you have room on the stack for these. If M and N are expected to be large,put this on the heap instead
double bp[M*N];
double cp[M*N];
for (int i = 0; i < M; ++i) {
memcpy(ap + i * N,A[i],N * sizeof(ap[0]));
memcpy(bp + i * N,B[i],N * sizeof(bp[0]));
memcpy(cp + i * N,C[i],N * sizeof(cp[0]));
}
qsort(ap,M*N,sizeof(ap[0]),doublecomp);
qsort(bp,sizeof(bp[0]),doublecomp);
qsort(cp,sizeof(cp[0]),doublecomp);
return !(memcmp(ap,bp,M*N*sizeof(ap[0])) || memcmp(ap,cp,M*N*sizeof(ap[0])));
}
我觉得这很好读。它处理任意双精度值(您可以根据您的实际需求调整比较函数,例如使用 DBL_EPSILON
)。而且,假设您可能有任意双精度,这可能与为直方图构建一些映射一样有效。
bool is_permutation(int m1[][NUM_COLS],int m2[][NUM_COLS],int n)
{
int i,j,num1,num2;
int m1_counts[MAX_NUM] = {0};
int m2_counts[MAX_NUM] = {0};
for (i = 0; i < n; i++)
for (j = 0; j < NUM_COLS; j++) {
num1 = m1[i][j];
num2 = m2[i][j];
if (0 <= num1 && num1 < MAX_NUM &&
0 <= num2 && num2 < MAX_NUM) {
m1_counts[num1]++;
m2_counts[num2]++;
} else {
fprintf(stderr,"Error: out of bounds");
exit(EXIT_FAILURE);
}
}
for (i = 0; i < MAX_NUM; i++)
if (m1_counts[i] != m2_counts[i])
return false;
return true;
}
#define ARE_PERMUTATIONS(m1,m2,m3,n) \
(is_permutation((m1),(m2),(n)) && \
is_permutation((m1),(m3),(n)) && \
is_permutation((m2),(n)))
#define PRINT_ARE_PERMUTATIONS(m1,n) \
printf(#m1 "," #m2 ",and " #m3 " %s permutations\n",\
ARE_PERMUTATIONS((m1),(n)) ? \
"are" : "are not")
PRINT_ARE_PERMUTATIONS(m1,NUM_COLS);
m3[2][2] = 1;
PRINT_ARE_PERMUTATIONS(m1,NUM_COLS);
m3[1][2] = 3;
PRINT_ARE_PERMUTATIONS(m1,NUM_COLS);
m2[2][2] = 10;
PRINT_ARE_PERMUTATIONS(m1,NUM_COLS);
@H_696_55@