-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIOUtils.java
78 lines (65 loc) · 2.34 KB
/
IOUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.*;
import java.io.BufferedReader;
import java.io.File; // Import the File class
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException; // Import the IOException class to handle errors
/**
*
* @author Luca Crema
* @param <I> InputData type
*/
public class IOUtils {
public static ProblemData readInputFile(String filename) throws FileNotFoundException, IOException {
File file = new File(filename);
Scanner sc = new Scanner(file);
// first line has scan days
String[] firstLine = sc.nextLine().split(" ");
int scanningDays = Integer.parseInt(firstLine[2]);
// second line has books and values
String[] booksValuesTXT = sc.nextLine().split(" ");
int[] booksValues = new int[booksValuesTXT.length];
for (int i = 0; i < booksValuesTXT.length; i++) {
booksValues[i] = Integer.parseInt(booksValuesTXT[i]);
}
List<Library> libraries = new ArrayList<Library>();
int currentLibraryName = 0;
// all other lines have libraries data
while (sc.hasNextLine()) {
String[] libraryData = sc.nextLine().split(" ");
if (libraryData.length < 3)
break;
int signupDays = Integer.parseInt(libraryData[1]);
int parallelCount = Integer.parseInt(libraryData[2]);
String[] libraryBooksTXT = sc.nextLine().split(" ");
if (libraryBooksTXT.length <= 0)
break;
List<Book> libraryBooks = new ArrayList<Book>();
for (String bookIDTXT : libraryBooksTXT) {
int bookID = Integer.parseInt(bookIDTXT);
Book book = new Book(bookID, booksValues[bookID]);
libraryBooks.add(book);
}
Collections.sort(libraryBooks, new BookComparator());
Library library = new Library(currentLibraryName, libraryBooks, signupDays, parallelCount);
libraries.add(library);
currentLibraryName++;
}
return new ProblemData(libraries, scanningDays);
}
public static void writeOutputFile(OutputData data, String filename) throws IOException {
createFile(filename);
writeToFile(filename, data.getOutput());
}
private static void createFile(String filename) throws IOException {
File file = new File(filename);
if (!file.exists())
file.createNewFile();
}
private static void writeToFile(String filename, String content) throws IOException {
FileWriter fileWriter = new FileWriter(filename);
fileWriter.write(content);
fileWriter.close();
}
}