Issue
I have given a two-dimensional array (matrix) and the two numbers: i and j. My goal is to swap the columns with indices i and j within the matrix. Input contains matrix dimensions n and m, not exceeding 100, then the elements of the matrix, then the indices i and j.
I guess the origin of the problem has something to do with referenced variables? I tried to replace line 15 with
int nextValue = scanner.nextInt();
matrix[i][j] = nextValue;
swap[i][j] = nextValue;
but still the output remains the same...
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int row = scanner.nextInt();
int column = scanner.nextInt();
int[][] matrix = new int[row][column];
int[][] swap = matrix.clone();
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
matrix[i][j] = scanner.nextInt();
}
}
int c0 = scanner.nextInt();
int c1 = scanner.nextInt();
for (int i = 0; i < row; i++) {
swap[i][c0] = matrix[i][c1];
swap[i][c1] = matrix[i][c0];
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
System.out.print(swap[i][j] + " ");
}
System.out.println();
}
}
}
My Input:
3 4
11 12 13 14
21 22 23 24
31 32 33 34
0 1
3 and 4 stands for the number of rows and columns of the matrix, the following three lines define the elements of the matrix and the last line tells the program which columns so swap.
Expected Output:
12 11 13 14
22 21 23 24
32 31 33 34
Actual Output:
12 12 13 14
22 22 23 24
32 32 33 34
Solution
It looks like your swapping logic is off. If you want to swap two variables, say a
and b
, then here is a pattern which works in Java:
int a = 5;
int b = 10;
int temp = a;
a = b;
b = temp;
Applying this logic to your matrix column swap, we can try the following updated code:
int c0 = scanner.nextInt();
int c1 = scanner.nextInt();
for (int i=0; i < row; i++) {
int temp = matrix[i][c0];
matrix[i][c0] = matrix[i][c1];
matrix[i][c1] = temp;
}
Answered By - Tim Biegeleisen
Answer Checked By - Senaida (JavaFixing Volunteer)