【发布时间】:2020-11-21 06:23:42
【问题描述】:
这是我通过使用邻接矩阵来查找关系是否等价并计算等价类的代码
#include <stdio.h>
#include <string.h>
int mat[10][10], setln, relln, n, i, j;
char set[10], rel[50];
int checkrel(char);
int reflexive();
int symmetric();
int transitive();
int display();
int adjacency();
void main()
{
int check = 1, r, s, t;
printf("Enter the no. of elements in the set: ");
scanf("%d", &n);
gets(set);
printf("Enter the elements of the set: ");
fgets(set, 10, stdin);
setln = strlen(set);
while (check == 1)
{
printf("\nEnter the elements of relation in the manner '(a,b)(b,d)...':\n");
fgets(rel, 50, stdin);
relln = strlen(rel);
if (relln < 5)
continue;
for (i = 0; i < relln - 5; i + 5)
{
if (rel[0] == '(' && (checkrel(rel[1])) && rel[2] == ',' && (checkrel(rel[3])) && rel[4] == ')')
check = 0;
else
{
printf("Enter a valid relation");
break;
}
}
}
adjacency();
r = reflexive();
s = symmetric();
t = transitive();
if (r == 1)
printf("\nThe relation is reflexive");
else
printf("\nThe relation is not reflexive");
if (s == 1)
printf("\nThe relation is symmetric");
else
printf("\nThe relation is not symmetric");
if (t == 1)
printf("\nThe relation is transitive");
else
printf("\nThe relation is not transitive");
if (r == 1 && s == 1 && t == 1)
printf("\nTherefore the relation is equivalent");
else
printf("\nTherefore the relation is not equivalent");
int display();
getchar();
}
int checkrel(char a)
{
int m;
for (int i = 0; i < setln; i++)
{
if (a == set[i])
m = 1;
}
if (m == 1)
return 1;
else
return 0;
}
int adjacency()
{
int a, b;
for (i = 1, j = 3; i < relln - 3; i + 5, j + 5)
{
for (int k = 0; k < setln; k++)
{
if (rel[i] == set[k])
a = k;
}
for (int l = 0; l < setln; l++)
{
if (rel[j] == set[l])
b = l;
}
mat[a][b] = 1;
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (mat[i][j] != 1)
mat[i][j] = 0;
}
}
}
int reflexive()
{
for (i = 0; i < n; i++)
{
if (mat[i][i] != 1)
{
return 0;
}
}
return 1;
}
int symmetric()
{
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (mat[i][j] != mat[j][i])
{
printf("\nThe relation is not equivalent as it is not symmetric");
return 0;
}
}
}
return 1;
}
int transitive()
{
int k;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (mat[i][j] == 1)
{
for (k = 0; k < n; k++)
{
if (mat[j][k] == 1 && mat[i][k] != 1)
{
printf("\nThe relation is not equivalent as it is not transitive");
return 0;
}
}
}
}
}
return 1;
}
int display()
{
printf("\nThe equivalence class is:\n{");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (mat[i][j] == 1)
printf("(%c,%c)", set[i], set[j]);
}
}
printf("}\n");
}
vscode 终端中的输出只是在此之后停止并且不会终止
Enter the no. of elements in the set: 3
Enter the elements of the set: 123
Enter the elements of relation in the manner '(a,b)(b,d)...':
(1,1)(2,2)
^C
D:\c>
光标只是固定在 (1,1)(2,2) 行之后的换行符中,直到我按 ctrl+c 我最后使用了 getchar() 但它不起作用
【问题讨论】:
标签: c set adjacency-matrix