Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Capriatto/572d34d750fae745a4bc to your computer and use it in GitHub Desktop.
Save Capriatto/572d34d750fae745a4bc to your computer and use it in GitHub Desktop.
This example allows you interchange a matrix column.
import javax.swing.JOptionPane;
/**
*
* @author coder
*/
public class IntercambiarColumna {
public static void main(String[] args) {
new IntercambiarColumnas().imprimir();
}
private int[][] init() {
int filas = Integer.parseInt(JOptionPane.showInputDialog("Nro filas de la matriz"));
int columnas = Integer.parseInt(JOptionPane.showInputDialog("Nro columnas de la matriz"));
int m[][] = new int[filas][columnas];
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m.length; j++) {
m[i][j] = (int) (Math.random() * 10);
}
}
return m;
}
private void imprimir() {
System.out.println("MATRIZ ORIGINAL");
int[][] b = init().clone();
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b.length; j++) {
System.out.print(b[i][j] + "\t");
}
System.out.print("\n");
}
// intercambiar columnas
intercambiarColumnas(b);
}
// here is the alghoritm
private void intercambiarColumnas(int[][] c) {
int columnaOrigen= Integer.parseInt(JOptionPane.showInputDialog("¿Columna que deseas cambiar?")) - 1;
int columnaDestino = Integer.parseInt(JOptionPane.showInputDialog("¿Por cual columna la vas a cambiar?")) - 1;
int auxiliar;
for (int i = 0; i < c.length; i++) {
auxiliar = c[i][columnaDestino];
c[i][columnaDestino] = c[i][columnaOrigen];
c[i][columnaOrigen] = auxiliar;
}
imprimirResultado(c);
}
private void imprimirResultado(int c[][]) {
System.out.println(" ----------------------------------");
System.out.println("MATRIZ MODIFICADA");
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c.length; j++) {
System.out.print(c[i][j] + "\t");
}
System.out.print("\n");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment