-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWriter.java
104 lines (90 loc) · 2.11 KB
/
Writer.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* Writer.java
*
* Class that contains a string list to be written in a log file.
*
* @author: James M. Bayon-on
* @version: 1.3
*/
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class Writer {
private ArrayList<String> list;
/* Instantiates the writer class.
*
*/
public Writer() {
list = new ArrayList<String>();
}
/* Accepts a string to add to the string list in the writer class.
*
* @param: a line string to write into the log
*/
public void add(String line) {
list.add(line);
}
/* Accepts a particle and converts the content solution into strings then adds it to the string list.
*
* @param: a particle to write into the log
*/
public void add(Particle p) {
int n = p.getMaxLength();
String board[][] = new String[n][n];
clearBoard(board, n);
for(int x = 0; x < n; x++) {
board[x][p.getData(x)] = "Q";
}
printBoard(board, n);
}
/* Clears a 2D string board with empty string.
*
* @param: a 2D string board
* @param: length of n
*/
public void clearBoard(String[][] board, int n) {
// Clear the board.
for(int x = 0; x < n; x++) {
for(int y = 0; y < n; y++) {
board[x][y] = "";
}
}
}
/* Replaces the position of the queens with Q in the string board and a dot for indexes with no queens.
*
* @param: a 2D string board
* @param: length of n
*/
public void printBoard(String[][] board, int n) {
// Display the board.
for(int y = 0; y < n; y++) {
String temp = "";
for(int x = 0; x < n; x++) {
if(board[x][y] == "Q") {
temp += "Q ";
} else {
temp += ". ";
}
}
list.add(temp);
}
}
/* Writes the string list into a log file.
*
* @param: a string filename
*/
public void writeFile(String filename) {
try{
FileWriter fw = new FileWriter(filename);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < list.size(); i++) {
bw.write(list.get(i));
bw.newLine();
bw.flush();
}
bw.close();
} catch (IOException e) {
System.out.println("Writing failed");
}
}
}