c - 如何在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]”。
提前致谢。
解决方案
您可以采用两遍方法:
- 第一遍:查找数组中的最大元素
- 第二遍:查找数组值等于最大元素的所有索引
为了存储多个位置,您可以在第二遍扫描数组时拥有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++;
}
}
}
推荐阅读
- reactjs - Opentok React:如何调用OTPublisher的Publisher对象的getStats方法?
- postgresql - Laravel 模型使用 ltrees 的 postgresql `subpath` 函数获取子路径
- javascript - 使用来自对象的行创建表
- javascript - ios上的jQuery滚动问题
- simulink - dsPIC 挂起带有 simulink 代码生成器的扩展卡尔曼滤波器
- database - TYPO3 Extbase 查询总是超级慢
- javascript - 本地存储是未定义的 jQuery
- react-native - 如何将两个文本左对齐和居中对齐而不在 react-native 中添加 paddingLeft、margin left ad right 值
- javascript - Toggleclass 以动态颜色突出显示
- python - SettingWithCopyWarning:不支持对 datetimelike 对象的方法进行修改并被丢弃