0

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!

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
Lost Soul
  • 345
  • 1
  • 3
  • 8
  • the array has come out as a long line of numbers it is meant to be shown as 4x4 – Lost Soul Mar 30 '16 at 16:28
  • 2
    If it is an array of arrays, then reversing a "row" is simply reversing a particular array. There is plenty of information on how to [reverse an array](http://stackoverflow.com/questions/2137755/how-do-i-reverse-an-int-array-in-java). – KevinO Mar 30 '16 at 16:31
  • Your code looks okay to me. You want to tell what errors/issues you have with the given code? – user2004685 Mar 30 '16 at 16:37
  • 1
    your code is ok, but you don't need to iterate over `i`. Set `i` once to value of user input, and remove outer loop. – Alex Salauyou Mar 30 '16 at 16:37

2 Answers2

0

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; }

 }
Chris Conaty
  • 93
  • 1
  • 1
  • 10
0

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;
}
Ido Michael
  • 109
  • 7