如有语法错误,请见谅。
我会尽力解释我的问题是哪个问题。
我正在处理一个二维数组,从数组的一个点开始,我应该打印两个水平、垂直和倾斜的附近单元格。
黄色单元格是起点,红色和灰色单元格是我必须打印的单元格。
我发现的解决方案是制作 4 种不同的算法:一种打印水平单元格,另一种打印垂直单元格,另一种打印倾斜单元格(从右到左),另一种打印水平单元格倾斜单元格(从左到右)。
所以我解决这个问题就像我在处理 vector 一样,我认为这是一个非常糟糕的解决方案。
水平打印示例:
int startPos=0;
int counter=5; //Five and not four, because it includes the start point that hasn't to be printed
if(column >= 2) startPos = column - 2;
else counter -= (2-column);
for(i=0; i<counter; i++){
if(startPos + i != column){ //the start point hasn't to be printed
printf("m-array[%d][%d] ", row, startPos + i);
}
}
我从起点返回两个单元格,然后打印接下来的四个单元格。
最佳答案
如果您希望 4 个“不同”算法为 1,您只需找到它们之间共享的逻辑,并创建一个实现它的函数即可。
共享的部分是它们都打印一行。每行从不同的位置开始,并以不同的方向打印。我将此函数称为 printLine。
请注意,我创建的函数可以使用静态和动态分配的数组。
您可以以不同的方式实现它。具体来说,您可以组合两个 for 循环并添加一个测试以防止打印主单元格。
#include <stdio.h>
int isInBounds(int rows, int cols, int y, int x) {
return (y >= 0) && (y < rows) && (x >= 0) && (x < cols);
}
void printLine(int *array, // pointer to start of the array
int rows, int cols, // amount of rows and columns
int count, // how many steps before and after the given cell
int posY, int posX, // the position of the cell to print around
int dirY, int dirX) { // the direction to advance each time
int y = posY - count * dirY;
int x = posX - count * dirX;
int i = 0;
// loop till we get to the given cell
// increase y and x according to dirY and dirX
for(i = 0; i < count; i++, y += dirY, x += dirX) {
if(isInBounds(rows, cols, y, x)) {
// don't print if this cell doesn't exist
printf("Array[%d][%d] = %d\n", y, x, array[y * cols + x]);
}
}
y = posY + dirY;
x = posX + dirX;
// loop count times, starting 1 step after the given cell
for(i = 0; i < count; i++, y += dirY, x += dirX) {
if(isInBounds(rows, cols, y, x)) {
// don't print if this cell doesn't exist
printf("Array[%d][%d] = %d\n", y, x, array[y * cols + x]);
}
}
}
void main(void) {
int rows = 5;
int cols = 8;
int array[rows][cols]; // array is uninitialized
int count = 2; // you wanted to print 5 without middle, which means 2 from each side
int posY = 2;
int posX = 3;
/*************************
* initialize array here */
int i = 0;
for(; i < rows * cols; i++) {
*(((int *)array) + i) = i;
}
/************************/
printLine((int *)array, rows, cols,
count,
posY, posX,
1, 0); // move 1 row down
printLine((int *)array, rows, cols,
count,
posY, posX,
0, 1); // move 1 column to the right
printLine((int *)array, rows, cols,
count,
posY, posX,
1, 1); // move 1 row and column, so down and right
printLine((int *)array, rows, cols,
count,
posY, posX,
-1, 1); // same as last diagonal but now up and right
}
关于C:打印数组中某个点的水平、垂直和倾斜值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46112842/