I'm having trouble implementing a text justification algorithm on a large book.The program is able to take in smaller passages but once I load in the whole book I get a memory leak. More importantly, my algorithm is not putting the right amount of characters on a single line. I'm not quite sure why this is but if someone can please take a look at this and help me figure it out it will be greatly appreciated!
public class TextJustification {
public String justify(String words[], int width) {
int cost[][] = new int[words.length][words.length];
//next 2 for loop is used to calculate cost of putting words from
//i to j in one line. If words don't fit in one line then we put
//Integer.MAX_VALUE there.
for (int i = 0; i < words.length; i++) {
cost[i][i] = width - words[i].length();
for (int j = i + 1; j < words.length; j++) {
cost[i][j] = cost[i][j - 1] - words[j].length() - 1;
}
}
for (int i = 0; i < words.length; i++) {
for (int j = i; j < words.length; j++) {
if (cost[i][j] < 0) {
cost[i][j] = Integer.MAX_VALUE;
} else {
cost[i][j] = (int) Math.pow(cost[i][j], 2);
}
}
}
//minCost from i to len is found by trying
//j between i to len and checking which
//one has min value
int minCost[] = new int[words.length];
int result[] = new int[words.length];
for (int i = words.length - 1; i >= 0; i--) {
minCost[i] = cost[i][words.length - 1];
result[i] = words.length;
for (int j = words.length - 1; j > i; j--) {
if (cost[i][j - 1] == Integer.MAX_VALUE) {
continue;
}
if (minCost[i] > minCost[j] + cost[i][j - 1]) {
minCost[i] = minCost[j] + cost[i][j - 1];
result[i] = j;
}
}
}
int i = 0;
int j;
System.out.println("Minimum cost is " + minCost[0]);
System.out.println("\n");
//finally put all words with new line added in
//string buffer and print it.
StringBuilder builder = new StringBuilder();
do {
j = result[i];
for (int k = i; k < j; k++) {
builder.append(words[k] + " ");
}
builder.append("\n");
i = j;
} while (j < words.length);
return builder.toString();
}
public static void main(String args[]) throws IOException {
File read = new File("TaleOfTwoCities.txt");
Scanner in = new Scanner(read);
ArrayList<String> temporary = new ArrayList<String>();
while (in.hasNext()) {
temporary.add(in.next());
}
String[] words1 = temporary.toArray(new String[temporary.size()]);
//String words1[] = {"I", "am", "so", "stuck,", "please,", "help", "me"};
TextJustification awl = new TextJustification();
System.out.println(awl.justify(words1, 60));
}
}
Here is my code I hope someone is able to help me out as I have been scratching my head for a few days. Also the link to the txt file I am trying to parse is https://www.dropbox.com/s/5sy5zp4n3b6wgfz/TaleOfTwoCities.txt?dl=0 Thanks again guys and hope someone can help out!
EDIT: This is an image of how I am trying to justify the text since I didn't make that clear enough before: https://www.dropbox.com/s/f9xt83nflwj1q5p/project1.png?dl=0