msmtdg
BAN USERFind the line which is unique, show it's index.
Short circuit the read if the unique line is found.
Must read no less than three lines if the line count is > 3.
1. Read each line of the file.
2. The first line is compared to each consecutive line, noting the line count.
3. When the line that is unique is encountered, report that line number and exit.
public void readFileLines(String fileName) {
try {
File file = new File(fileName);
FileReader fileReader = new FileReader(file);
BufferedReader bufRead = new BufferedReader(fileReader);
String line1 = new String();
String line2 = new String();
String lineNext = new String();
// Line count to identify which line is different than the rest.
int count = 0;
while ((lineNext = bufRead.readLine()) != null && !lineNext.isEmpty()) {
++count;
if (!line1.isEmpty() && !lineNext.equals(line1)) {
line2 = lineNext;
if ((lineNext = bufRead.readLine()) != null) {
++count;
if (lineNext.equals(line1)) {
System.out.println("Line[" + (count-1) + "] is unique: \"" + line2 + "\"");
}
else if (lineNext.equals(line2)) {
System.out.println("Line[" + (0) + "] is unique: \"" + line1 + "\"");
}
System.out.println("The other Lines : \"" + lineNext + "\"");
}
break;
}
else {
if (line1.isEmpty()) {
line1 = lineNext;
}
}
}
if (!line1.isEmpty() && line2.isEmpty()) {
System.out.println("All lines in input file are the same. There are " + count + " lines.");
System.out.println("Each line is: \"" + line1 + "\"");
}
}
catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
}
@Kanha
Your algorithm returns {{1,5},{2,4},{3,3},{6}} when there is only one 3 in the set
array problem set of{1,2,3,4,5,6}.
Your inner loop index should be initialized 1 beyond the outer loop to avoid comparing a[i] to itself when j == i. Better to initialize j with [ j = i + 1;]. Like this for(int j=i+1; j<a.length; j++).
Can use recursion here efficiently. It works in both C# and Java as the left, right and next Node elements are references to the objects allocated for the tree. This is cheap in use of space. Each call stack has a reference to the original root node defined in your main.
- msmtdg May 06, 2015