下面是你需要做的伪代码。
for row in grid {
row_max = max_in_row(row)
grid_min = min(grid_min, row_max)
}
第一步是编写一个例程,在列表中找到最大值和位置。你可以将它作为一个大功能来完成,但是它更容易理解和调试。
您还需要找到它的索引。由于C无法返回多个值,因此我们需要一个结构来存储数字/索引对。每当你创建一个结构体时,都要创建和销毁它的例程。对于像这样微不足道的东西看起来似乎有点过分,但它会让你的代码更容易理解和调试。
typedef struct {
int num;
size_t idx;
} Int_Location_t;
static Int_Location_t* Int_Location_new() {
return calloc(1, sizeof(Int_Location_t));
}
static void Int_Location_destroy(Int_Location_t* loc) {
free(loc);
}
现在我们可以做一个小函数来查找连续的最大数量和位置。
static Int_Location_t* max_in_row(int *row, size_t num_rows) {
Int_Location_t *loc = Int_Location_new();
/* Start with the first element as the max */
loc->num = row[0];
loc->idx = 0;
/* Compare starting with the second element */
for(size_t i = 1; i < num_rows; i++) {
if(row[i] > loc->num) {
loc->num = row[i];
loc->idx = i;
}
}
return loc;
}
,而不是与一些任意最大或最小起,我使用的备选技术,其中我设置最大为第一元件,然后开始从第二个检查。现在,我有一个函数来找到一排最大
,我现在可以遍历它,得到各行的最大值,并与最低为整个表进行比较。
int main() {
int grid[3][3] = {
{10, 12, 15},
{-50, -15, -10},
{1,2,3}
};
int min = INT_MAX;
size_t row = 0;
size_t col = 0;
for(size_t i = 0; i < 3; i++) {
Int_Location_t *max = max_in_row(grid[i], 3);
printf("max for row %zu is %d at %zu\n", i, max->num, max->idx);
if(max->num < min) {
min = max->num;
col = max->idx;
row = i;
}
Int_Location_destroy(max);
}
printf("min for the grid is %d at row %zu, col %zu\n", min, row, col);
}
我使用了不同的技术来初始化最小位置,因为获取第一个最大值需要在循环中重复一些代码。相反,我将min设置为尽可能最低的整数,INT_MAX来自limits.h,这是可能的最高整数。这允许代码与任何整数范围一起使用,没有限制。使用最小/最大算法时,这是一种非常常见的技术。