Instantly share code, notes, and snippets.
Created
May 31, 2016 16:10
-
Star
0
(0)
You must be signed in to star a gist -
Fork
0
(0)
You must be signed in to fork a gist
-
Save ckob/3c92109ca53c588288cad04e9cb763d4 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
package KochCarles; // cal canviar-lo al teu nom | |
import java.io.*; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Comparator; | |
/* | |
* Copyright 2016 Carles Koch Busquets | |
* | |
* This is free software, licensed under the GNU General Public License v3. | |
* See http://www.gnu.org/licenses/gpl.html for more information. | |
*/ | |
public class Examen{ | |
/** | |
* | |
* @param str string a moldejar | |
* @param length la longitud desitgada del string | |
* @param JUST left, center or rigth | |
* @return | |
*/ | |
private static String fitStrToLength(String str, int length, JUSTIFY_TYPE JUST) { | |
if (JUST == JUSTIFY_TYPE.LEFT) { | |
for (int i = str.length(); i < length; i++) | |
str += " "; | |
} else if (JUST == JUSTIFY_TYPE.RIGTH) { | |
for (int i = str.length(); i < length; i++) | |
str = " " + str; | |
} else if (JUST == JUSTIFY_TYPE.CENTER) { | |
for (int i = str.length(); i < length; i++) | |
str = i%2==0 ? str+" ": " "+str; | |
} | |
return str; | |
} | |
/** | |
* enums | |
*/ | |
public enum JUSTIFY_TYPE { | |
LEFT, CENTER, RIGTH; | |
} | |
/** | |
* @param content arraylist amb el contingut | |
* @param camp camp a ordenar per | |
* @param asc especificar si es vol ordenar ascendentment (true) o descendentment (false) | |
* @return true if the order worked | |
*/ | |
public static boolean orderArr(ArrayList<String[]> content, final int camp, final boolean asc) { // Ordena la taula a partir de la fila donada (string numeric) | |
Collections.sort(content, new Comparator<String[]>() { | |
@Override | |
public int compare(String[] str1, String[] str2) { | |
if (str1[camp].isEmpty()) | |
return asc ? -1 : 1; | |
if (str2[camp].isEmpty()) | |
return asc ? 1 : -1; | |
if (asc) | |
return (int) (Integer.parseInt(str1[camp]) - Integer.parseInt(str2[camp])); | |
else | |
return (int) (Integer.parseInt(str2[camp]) - Integer.parseInt(str1[camp])); | |
} | |
}); | |
return true; | |
} | |
/** | |
* @param content | |
* @param columns començant per 0, columns a obtenir en un nou arraylist | |
* @return | |
*/ | |
public static ArrayList<String[]> getColumns(ArrayList<String[]> content, int... columns) { | |
ArrayList<String[]> newContent = new ArrayList<>(content.size()); | |
for (String[] line : content) { | |
String[] newLine = new String[columns.length]; | |
int i = 0; | |
for (int column : columns) { | |
newLine[i] = line[column]; | |
i++; | |
} | |
newContent.add(newLine); | |
} | |
return newContent; | |
} | |
/** | |
* @param text un string separat amb estil csv | |
* @return array de Strings amb un valor per cada camp separat correctament. | |
*/ | |
public static String[] liniaCsvToArrString(String text, char possibleDelimitadorCamps, char separadorCamps) { | |
ArrayList<String> strings = new ArrayList<>(); | |
String str = ""; | |
boolean entreCometes = false; | |
for (int i = 0; i < text.length(); i++) { | |
if (text.charAt(i) == possibleDelimitadorCamps) { | |
if (i + 1 < text.length()) { | |
if ((text.charAt(i + 1) == possibleDelimitadorCamps)) { // Escapar cometes | |
str += text.charAt(i); // Afegeixo unes cometes de les dues que hi han. | |
i++; // i ja no cal mirar les següents | |
} else { | |
entreCometes = !entreCometes; | |
} | |
continue; | |
} else if (i == text.length() - 1) { // evitar l'ultim possible delimitador de la linia | |
break; | |
} | |
} | |
if (text.charAt(i) == separadorCamps && !entreCometes) { | |
strings.add(str); | |
str = ""; | |
} else { | |
str += text.charAt(i); | |
} | |
} | |
strings.add(str); // ultim camp | |
return strings.toArray(new String[strings.size()]); | |
} | |
/** | |
* Get the content of a file, from line number to the end of the file | |
* | |
* @param entryFile file of the content | |
* @return arraylist with the content of the file | |
*/ | |
public static ArrayList<String[]> fileCsvToArrayList(String entryFile, int startLine, char fieldSeparator, char charToSurroundField) { | |
ArrayList<String[]> fileContent = new ArrayList<>(); | |
BufferedReader br = null; | |
try { | |
br = new BufferedReader(new FileReader(entryFile)); | |
String actualLine; | |
for (int i = 0; i < startLine; i++) { | |
br.readLine(); | |
} | |
while ((actualLine = br.readLine()) != null) { | |
fileContent.add(liniaCsvToArrString(actualLine, charToSurroundField, fieldSeparator)); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} finally { | |
try { | |
if (br != null) | |
br.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
return fileContent; | |
} | |
/** | |
* Process input file according to especifications | |
* | |
* prints (console) a summary of equipments | |
* sorted by events that have taken place | |
* | |
* produces an output file that contains html code | |
* representing the csv sorted by equipment | |
* | |
* | |
* @param arxiuEntrada input file (csv) | |
* @param arxiuSortida output file (html) | |
* @param fieldSeparator usually , | |
* @param charToSurroundField usually " | |
* @return false if input does not exist | |
*/ | |
public boolean examenUF31516ord(String arxiuEntrada, String arxiuSortida, | |
char fieldSeparator, char charToSurroundField) { | |
File file = new File(arxiuEntrada); | |
if (!file.exists() || !file.isFile()) { | |
return false; // Si el fitxer no existeix, retorno fals. En cas contrari, retorno true al final de tot. | |
} | |
ArrayList<String[]> content = fileCsvToArrayList(arxiuEntrada, 1, fieldSeparator, charToSurroundField); | |
content = getColumns(content, 3, 18); | |
ArrayList<Integer> ids = new ArrayList<>(); | |
for (String[] line : content) { | |
if (!ids.contains(Integer.parseInt(line[0]))) { | |
ids.add(Integer.parseInt(line[0])); | |
} | |
} | |
int[] preus = new int[ids.size()]; | |
int[] nEvents = new int[preus.length]; | |
int[] min = new int[preus.length]; | |
int[] max = new int[preus.length]; | |
double[] avg = new double[preus.length]; | |
for (String[] line : content) { | |
int idtmp= ids.indexOf(Integer.parseInt(line[0])); | |
int num; | |
if (line[1] == null || line[1].isEmpty()) { | |
num = 0; | |
} else { | |
num = Integer.parseInt(line[1]); | |
} | |
nEvents[idtmp]++; | |
preus[idtmp]+=num; | |
if (num<min[idtmp]) { | |
min[idtmp]=num; | |
} | |
if (num>max[idtmp]) { | |
max[idtmp]=num; | |
} | |
} | |
for (int i = 0; i < preus.length; i++) { | |
avg[i] = (double)preus[i]/(double)nEvents[i]; | |
} | |
int[][] minMaxAvg = new int[preus.length][3]; | |
for (int i = 0; i < preus.length; i++) { | |
minMaxAvg[i][0] = preus[i]; | |
} | |
int[] maxLengthFields = new int[5]; | |
for (int i = 0; i < ids.size(); i++) { | |
maxLengthFields[0]=Math.max(maxLengthFields[0], String.valueOf(ids.get(i)).length()); | |
maxLengthFields[1]=Math.max(maxLengthFields[1], String.valueOf(nEvents[i]).length()); | |
maxLengthFields[2]=Math.max(maxLengthFields[2], String.valueOf(min[i]).length()); | |
maxLengthFields[3]=Math.max(maxLengthFields[3], String.valueOf(max[i]).length()); | |
String avgStr = String.format("%.1f", avg[i]); | |
maxLengthFields[4]=Math.max(maxLengthFields[4], avgStr.length()); | |
} | |
ArrayList<String[]> finalArr = new ArrayList<>(preus.length); | |
for (int i = 0; i < ids.size(); i++) { | |
String[] tmp = new String[5]; | |
tmp[0] = String.valueOf(ids.get(i)); | |
tmp[1] = String.valueOf(nEvents[i]); | |
tmp[2] = String.valueOf(min[i]); | |
tmp[3] = String.valueOf(max[i]); | |
tmp[4] = String.format("%.1f", avg[i]); | |
finalArr.add(tmp); | |
} | |
orderArr(finalArr, 1, false); | |
for (String[] strings : finalArr) { | |
for (int i = 0; i < strings.length; i++) { | |
strings[i]=fitStrToLength(strings[i],maxLengthFields[i],JUSTIFY_TYPE.RIGTH); | |
} | |
} | |
for (String[] line : finalArr) { | |
for (String s : line) { | |
System.out.print(s+"\t"); | |
} | |
System.out.println(); | |
} | |
// Segon exercici | |
ArrayList<String[]> contentv2 = fileCsvToArrayList(arxiuEntrada, 1, fieldSeparator, charToSurroundField); | |
orderArr(contentv2, 3, true); | |
String[] htmlEsc = { "agrave", "egrave", "ograve", "Agrave", | |
"Egrave", "Ograve", "aacute", "eacute", "iacute", "oacute", | |
"Oacute", "uacute", "ccedil", "middot", "euro", "iuml", | |
"uuml","quot", "#39", "nbsp", "rsquo", "ouml", "quot", | |
"ndash", "ntilde","amp" }; | |
ArrayList<String> html = new ArrayList<>(20); | |
html.add("<!DOCTYPE html charset=\"UTF-8\">\n" + | |
"<html>\n" + | |
"<head>"); | |
html.add("<title>Carles Koch</title>"); | |
html.add("<meta charset=\"UTF-8\">"); | |
html.add("<style>\n" + | |
"table, th, td {\n" + | |
"border: 1px solid black;\n" + | |
"text-align: center;\n" + | |
"}\n" + | |
".r {\n" + | |
"text-align: rigth;\n" + | |
"}\n" + | |
".l {\n" + | |
"text-align: left;\n" + | |
"}\n" + | |
"</style>\n" + | |
"</head>\n" + | |
"<body>"); | |
html.add("<table >"); | |
for (String[] line : contentv2) { | |
for (String esc : htmlEsc) { | |
line[2]=line[2].replaceAll("("+esc+"\\,){1}",esc); | |
} | |
html.add("<tr>"); | |
for (int j = 0; j < line.length; j++) { | |
html.add("<td class=l>"+line[j]+"</td>"); | |
} | |
html.add("</tr>"); | |
} | |
html.add("</table>\n" + | |
"</body>\n" + | |
"</html>"); | |
PrintWriter pw = null; | |
try { | |
pw = new PrintWriter(new BufferedWriter(new FileWriter(arxiuSortida))); | |
for (String s : html) { | |
pw.println(s); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} finally { | |
if (pw!=null) | |
pw.close(); | |
} | |
return true; | |
} | |
public static void main(String[] args) { | |
// si et surt el difícil, aquests dos pots estalviar-los | |
// new Examen().examenUF31516ord("agEasy.csv", "bonescape.html", ',', '"'); | |
// new Examen().examenUF31516ord("ag.csv", "bonescape.html", ',', '"'); | |
new Examen().examenUF31516ord("agDif.csv", "bonescape.html", ',', '"'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment