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:
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
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. 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...
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.