Collective Interview Question
Country: India
approach 1 : read F1 and F2 line by line and perform a regex such that only alphabets can be retrieved and compare the matches from both the results,do it till we reach end of the two files
If we reach the end of one file sooner, than the other, they are not equal.
approach 2: I am not sure about this, may be some one can give some feedback
create a hash of the file 1 and file 2 ignoring spaces and special characters, and if they are equal then the files are equal.
first you read chracter by character form file2 if it is a special charcater leave it ,after that you can read the character from the file1,if the file1 character is space leave it ,read next chracter and then compare the characters of the both the files .if they mathch go to next character until end of the file.Not match display files are not equal.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class CollectiveFile {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
{
// Open the file that is the first
// command line parameter
FileInputStream f1stream = new FileInputStream("textfile1.txt");
FileInputStream f2stream = new FileInputStream("textfile2.txt");
// Get the object of DataInputStream
DataInputStream in1 = new DataInputStream(f1stream);
DataInputStream in2 = new DataInputStream(f2stream);
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String strLine;
String strLine2;
//Read File Line By Line
while (((strLine = br1.readLine()) != null) && ((strLine2 = br2.readLine()) != null) )
{
strLine =removeSpecial(strLine);
strLine2=removeSpecial(strLine2);
if(strLine.equals(strLine2))
{
System.out.println("Matches");
}
else
{
System.out.println("Not Matches");
System.out.println (strLine2);
System.out.println (strLine);
break;
}
}
//Close the input stream
in1.close();
in2.close();
}
}
static String removeSpecial(String str)
{
str = str.replaceAll("\\W"," ");
str = str.replaceAll("\\s+"," ");
str = str.trim();
return str;
}
}
How about you have two read points, one for each file. And you just moving this read point on, ignoring the space or any extra character you want to ignore, comparing the character left one bye one, return fail if you got a mismatch or one reach EOF when the other not, return OK when each reach EOF at the same time.
- chenlc626 February 28, 2013