首页 > 解决方案 > 如何在C中存储多个二维数组位置?

问题描述

我正在尝试制作一个简单的程序,它将随机数生成为 15x15 2D 数组,然后稍后使用该数组。

此函数在数组中找到最大值,然后打印出该值及其位置。

void maxValue(int array[ROWS][COLUMNS]){
int maxNum = array[0][0];
int rowMaxLocation;
int columnMaxLocation;

for(int c = 0; c < ROWS; c++) {
    for(int d = 0; d < COLUMNS; d++) {
        if(maxNum < array[c][d]) {
            maxNum = array[c][d];
            rowMaxLocation = c;
            columnMaxLocation = d;
        }
    }
}

printf("Largest value in the array is %d, located in [%d][%d]", maxNum, rowMaxLocation, columnMaxLocation);
return;

我不知道如何存储相同最大值的多个位置,例如“数组中的最大值为 99,位于 [1][3] 和 [5][12]”。

提前致谢。

标签: cmultidimensional-array

解决方案


您可以采用两遍方法:

  • 第一遍:查找数组中的最大元素
  • 第二遍:查找数组值等于最大元素的所有索引

为了存储多个位置,您可以在第二遍扫描数组时拥有rowMaxLocations[]or数组并在其中存储相应的值。columnMaxLocations[]如果您不需要这些值,您可以简单地跳过将它们存储在某个数组中,也可以在第二遍中进行打印。

我建议使用 Location 结构来存储位置值,如下所示:

typedef struct Location {
    int row;
    int column;
} Location;

以下是这两次通过方法的样子:

void maxValue(int array[ROWS][COLUMNS]){
    int maxNum = array[0][0];
    // Array of locations to store max locations
    Location maxLocations[ROWS * COLUMNS];
    // Index of max locations array
    int maxLocationIndex = 0;

    // First pass; Get Max value
    for(int c = 0; c < ROWS; c++) {
        for(int d = 0; d < COLUMNS; d++) {
            if(maxNum < array[c][d]) {
                maxNum = array[c][d];
            }
        }
    }

    // Seconds pass; Get all values equal to max value
    for (int c = 0; c < ROWS; c++) {
        for (int d = 0; d < COLUMNS; d++) {
            if (array[c][d] == maxNum) {
                maxLocations[maxLocationIndex].row = c;
                maxLocations[maxLocationIndex].column = d;
                maxLocationIndex++;
            }
        }
    }

    // Print the max locations array
    printf("Largest value in the array is %d\n", maxNum);
    for (int i = 0; i < maxLocationIndex; i++) {
        printf("[%d][%d] \n", maxLocations[i].row, maxLocations[i].column);
    }
}

更新

感谢@Ian Abbott 的建议,还有一种方法可以一次性完成所有这些工作。maxLocationIndex每当我们找到一个新的最大值时,我们只需要重置:

    for(int c = 0; c < ROWS; c++) {
        for(int d = 0; d < COLUMNS; d++) {
            if(maxNum < array[c][d]) {
                maxNum = array[c][d];
                // Reset Max locations index
                maxLocationIndex = 0;
            }

            if (array[c][d] == maxNum) {
                maxLocations[maxLocationIndex].row = c;
                maxLocations[maxLocationIndex].column = d;
                maxLocationIndex++;
            }
        }
    }

推荐阅读