My code keeps failing because :
The program ran too long and was closed!
No idea why though
package com.codegym.task.task19.task1916;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/*
Tracking changes
*/
public class Solution {
public static List<LineItem> lines = new ArrayList<>();
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String file1 = reader.readLine();
String file2 = reader.readLine();
reader.close();
ArrayList<String> file1Contents = fileReader(file1);
ArrayList<String> file2Contents = fileReader(file2);
sameLines(file1Contents, file2Contents);
removedLines(file1Contents, file2Contents);
addedLines(file1Contents, file2Contents);
notConsecutive(lines);
}
public static enum Type {
ADDED, // New line added
REMOVED, // Line deleted
SAME // No change
}
public static class LineItem {
public Type type;
public String line;
public LineItem(Type type, String line) {
this.type = type;
this.line = line;
}
}
//read file lines and add to arraylist
public static ArrayList<String> fileReader(String fileName) throws IOException {
ArrayList<String> list = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String s;
while ((s = reader.readLine()) != null)
list.add(s);
}
return list;
}
//check if lines are the same
public static void sameLines(ArrayList<String> file1Contents, ArrayList<String> file2Contents){
for (String s : file1Contents){
if (file2Contents.contains(s))
lines.add(new LineItem(Type.ADDED, s));
}
}
//check if lines are removed
public static void removedLines(ArrayList<String> file1Contents, ArrayList<String> file2Contents){
for (String s : file1Contents){
if (!file2Contents.contains(s))
lines.add(new LineItem(Type.REMOVED, s));
}
}
//check if lines are added
public static void addedLines(ArrayList<String> file1Contents, ArrayList<String> file2Contents){
for (String s : file2Contents){
if (!file1Contents.contains(s))
lines.add(new LineItem(Type.ADDED, s));
}
}
// make sure removed & added are not consecutive
public static void notConsecutive(List<LineItem> lines){
for (int i = 0; i<lines.size()-1; i++){
if (lines.get(i).type==lines.get(i+1).type && lines.get(i).type!=Type.SAME){
insertSame(lines, i+1);
}
}
}
static int count = 0;
// insert same type between consecutive types
public static void insertSame(List<LineItem> lines, int index){
while (lines.get(count).type!=Type.SAME){
if (count == lines.size()-1)
count = 0;
else count++;
}
lines.add(index, lines.get(count));
}
}