Created
August 3, 2018 23:04
-
-
Save enmanuelr/8e48eb3131e749af8081427076399053 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.io.IOException; | |
import java.io.BufferedWriter; | |
import java.io.FileWriter; | |
import javax.swing.JOptionPane; | |
public class ColumnSort { | |
public static void main(String[] args) { | |
Scanner entrada = new Scanner(System.in); | |
int a[][]; | |
int nFilas, nCol; | |
nFilas = Integer.parseInt(JOptionPane.showInputDialog("Digite el numero de filas: ")); | |
nCol = Integer.parseInt(JOptionPane.showInputDialog("Digite el numero de columnas: ")); | |
a = new int[nFilas][nCol]; | |
// Ingresadon los datos de la matriz | |
System.out.println("Rellenando la matriz\n"); | |
for(int i=0; i<nFilas; i++){ | |
for(int j=0; j<nCol; j++){ | |
System.out.print("Matriz["+i+"]["+j+"]: "); | |
a[i][j] = entrada.nextInt(); | |
} | |
} | |
entrada.close(); | |
a = sort(a); | |
System.out.println("\nLa matriz sorteada es: "); | |
for(int i=0;i<nFilas;i++){ | |
for(int j=0;j<nCol;j++){ | |
System.out.print(a[i][j]+" "); | |
} | |
System.out.println(""); | |
} | |
write(a); | |
} | |
private static int[][] sort(int[][] matrix) { | |
ArrayList<Integer> list = new ArrayList<>(); | |
for(int i = 0; i < matrix.length; i++) { | |
for(int j = 0; j < matrix.length; j++) { | |
// Agregar cada columna a una lista | |
list.add(matrix[j][i]); | |
} | |
// Sortear la lista | |
Collections.sort(list); | |
for(int j = 0; j < matrix.length; j++) { | |
// re-insertar elementos sorteados a la columna | |
matrix[j][i] = list.get(j); | |
} | |
// limpear la lista para bregar la proxima vuelta | |
list.clear(); | |
} | |
return matrix; | |
} | |
private static void write(int[][] matrix) { | |
try { | |
// abrir un buffered writer para escribir al archivo | |
BufferedWriter writer = new BufferedWriter(new FileWriter("sorted-matrix.csv")); | |
// escribir cada linea separada por coma al archivo | |
for(int i = 0; i < matrix.length; i++) { | |
String line = toLine(matrix[i]); | |
writer.write(line); | |
writer.write("\n"); | |
} | |
// cerrar y guardar el contenido del archivo | |
writer.close(); | |
} catch(IOException e) { | |
System.err.println("Error al tratar de escirbir el archivo: " + e.getMessage()); | |
} | |
} | |
private static String toLine(int[] row) { | |
StringBuilder builder = new StringBuilder(); | |
for(int i = 0; i < row.length; i++) | |
builder.append(row[i]).append(","); | |
builder.deleteCharAt(builder.length() - 1); | |
return builder.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment