简体   繁体   English

如何反转4x4阵列中的一行

[英]how to reverse a row in a 4x4 array

I am fairly new to this an am unable to wrap my head around this. 我对此很陌生,无法解决这个问题。 I have basically been given a 4x4 array such as: 我基本上得到了一个4x4数组,例如:

5 2 1 7
3 2 4 4
7 8 9 2
1 2 4 3

I am trying to reverse specific rows, I am stuggling to find anything online about doing it for specific rows so I was wondering if anyone could give me an idea on how I could approach this. 我正在尝试反转特定行,我正努力在网上找到有关针对特定行执行此操作的任何信息,所以我想知道是否有人可以给我一个解决方法。

the desired output would be if a user asked for row 0 to be reversed then it would return 所需的输出将是如果用户要求将行0反转,则它将返回

7 1 2 5
3 2 4 4
7 8 9 2
1 2 4 3

i have attempted it but my code is not working. 我已经尝试过,但是我的代码无法正常工作。 This is my code: 这是我的代码:

for(int i = 0; i < row; i++){
for(int col = 0; col < cols / 2; col++) {
    int temp = arr[i][col];
    arr[i][col] = arr[i][arr[i].length - col - 1];
    arr[i][arr[i].length - col - 1] = temp;
}

Thanks in advance! 提前致谢!

Working with a specific row num and array, I beleive this will work. 使用特定的行num和数组,我相信这会起作用。 Try it out and let me know. 试试看,让我知道。

 function rowSwitch(row_num, arr) {

 for(int col = 0; col < arr[row_num].length/ 2; col++) {
     int temp = arr[row_num][col];
     arr[row_num][col] = arr[row_num][arr[row_num].length - col - 1];
     arr[row_num][arr[row_num].length - col - 1] = temp; }

 }

Ok, so first of all whenever you are running on a data structure, try not working on it. 好的,因此,首先,当您在数据结构上运行时,请尝试不对其进行处理。 Here you are changing the array by switching first and last, but what happens if the length is odd? 在这里,您通过先切换和后切换来更改数组,但是如果长度为奇数会怎样? there is a case which you didn't handled. 有一种情况您没有处理。 Secondly you are running on the wrong indexes, both arr[i].length == arr.length if this was not a square it would also have bugs... 其次,您在错误的索引上运行,都是arr [i] .length == arr.length如果这不是一个正方形,那么它也会有错误。

I would save a one dimensional array and switch it if you are having trouble with indexes. 如果您遇到索引问题,我将保存一维数组并进行切换。

Try using this code: 尝试使用以下代码:

for(int i = 0; i < arr.length / 2; i++)
{
    int temp = arr[i];
    arr[i] = arr[arr.length - i - 1];
    arr[arr.length - i - 1] = temp;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM