我想将一个数组中的值分配给另一个数组,但使用不同的数组 命令。例如原始数组将是:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
所需的数组是:
8 11 14 3 6 16 19
9 12 1 4 7 17 20
10 13 2 5 15 18 21
我该怎么做?在下面的代码中,我将选定的行移动到中心,然后单独分配每个数组。我想不出更好的办法。
int main()
{
int decide, i, j, k;
int save[3][7];
int shuffle[3][7];
int arr[3][7] = {
{1, 2, 3, 4, 5, 6, 7},
{8, 9, 10, 11, 12, 13, 14},
{15, 16, 17, 18, 19, 20, 21}
};
printf("Select a number between 1 and 21\n\n0-GroupA (1 - 7))\n1-GroupB ( 8 - 14)\n2-GroupC (15 - 21)\n\n");
for(k = 0 ; k < 1 ; ++k)
{
printf("Select which group the number falls into:");
scanf("%d", &decide);
for(j = 0 ; j < 7 ; ++j)
{/*moves selected row to middle row of array*/
save[0][j] = arr[1][j];
arr[1][j] = arr[decide][j];
arr[decide][j] = save[0][j];
}
/*this is a horrible method*/
shuffle[0][0] = arr[0][0];
shuffle[1][0] = arr[0][1];
shuffle[2][0] = arr[0][2];
shuffle[0][1] = arr[0][3];
shuffle[1][1] = arr[0][4];
shuffle[2][1] = arr[0][5];
shuffle[0][2] = arr[0][6];
shuffle[1][2] = arr[1][0];
shuffle[2][2] = arr[1][1];
shuffle[0][3] = arr[1][2];
shuffle[1][3] = arr[1][3];
shuffle[2][3] = arr[1][4];
shuffle[0][4] = arr[1][5];
shuffle[1][4] = arr[1][6];
shuffle[2][4] = arr[2][0];
shuffle[0][5] = arr[2][1];
shuffle[1][5] = arr[2][2];
shuffle[2][5] = arr[2][3];
shuffle[0][6] = arr[2][4];
shuffle[1][6] = arr[2][5];
shuffle[2][6] = arr[2][6];
}
最佳答案
像这样吗?
#include <stdio.h>
#define ROWS 3
#define COLS 7
int main(void){
int arr[ROWS][COLS] = {
{1, 2, 3, 4, 5, 6, 7},
{8, 9, 10, 11, 12, 13, 14},
{15, 16, 17, 18, 19, 20, 21}
};
int result[ROWS][COLS];
int order[ROWS] = {1, 0, 2};
int n = sizeof(arr)/sizeof(**arr);//number of elements
int r = 0, c = 0, i = 0, j = 0;
while(n--){
result[r++][c] = arr[order[i]][j++];
if(r == ROWS){
r = 0;
c += 1;
}
if(j == COLS){
j = 0;
i += 1;
}
}
//check print
for(r = 0; r < ROWS; ++r){
for(c = 0; c < COLS; ++c)
printf("%-2d ", result[r][c]);
puts("");
}
}
关于c - 如何重新排列二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44349064/