gpt4 book ai didi

c - 只打印 ARRAY[i][j] 不打印 ARRAY[j][i].... 删除二维数组的对角元素

转载 作者:行者123 更新时间:2023-11-30 19:30:26 25 4
gpt4 key购买 nike

我想打印数组的 [i][j] 个元素,并保留 [j][i] 个元素。

void printWeightList() {
//How many links there are: numOfEdges
int ARRAY[MAX][MAX];
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
ARRAY[i][j] = weightList[i][j];
}
}
int i = 0, j = 0;
for (i = 0; i < vertexCount; i++) {
for (j = 0; j < vertexCount; j++) {
if (ARRAY[i][j] != 0) {
printf("%c -> %c: ", lstVertices[i] ->label, lstVertices[j] ->label);
printf("%d\n", ARRAY[i][j]);
ARRAY[j][i] = 0; //TO REMOVE [j][i] ELEMENTS
}
}
}
printf("\n");
}

以上是我想到的一种解决方案。我不想更改weightList[][],因为它是全局定义的,所以我创建了另一个数组。这增加了空间复杂度。我想要一个不太复杂的解决方案。 Remove Diagonal Elements. Like (A, S), (B, S)

最佳答案

需要检查主对角线的条件是 j 等于 i。

#include <stdio.h>
#include <stdlib.h>

void printWeightList(void);

#define MAX 6

int weightList[MAX][MAX] = { 1, 2, 4 , 5 , 6, 7,
8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31,
32, 33, 34, 34, 35, 36,
};

int main (int argc, char *argv[])
{
printWeightList();

return(0);
}



void printWeightList(void) {

int ARRAY[MAX][MAX];
int i = 0;
int j = 0;

for ( i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
/*If we are on the main diagonal clear its elements*/
if (i == j) {
ARRAY[i][j] = 0;
}
else
{
ARRAY[i][j] = weightList[i][j];
}
}
}

for ( i = 0; i < MAX; i++) {
for ( j = 0; j < MAX; j++) {
printf("%d\t", ARRAY[i][j]);
}
printf("\n");
}

return;
}

关于c - 只打印 ARRAY[i][j] 不打印 ARRAY[j][i].... 删除二维数组的对角元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51000027/

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