icoderttc
BAN USERGiven how the problem is stated, you have a log file with the format above. If you set it up to have a LogEntry object like described above, then you will have to iterate through the list twice, which is not bad but there is a more efficient way to do it.
- Scan through the file, look for where the function first occur.
- Set startFunct = 1, endFunct = 0; Setting it this way, startFunct will always lead endFunct unless the corresponding ending function matches with the originally calling function.
- Create a variable to keep track of the time for even iteration count evenTime, and another one for odd iteration count oddTime. Time elapse is the difference between the even and the odd.
- Iterate until startFunct == endFunct, increment them along the way. Add time into the evenTime and oddTime.
Here is the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ElapseTime
{
public int getElapsedTime( String fileName, String startFunct, String endFunct ) throws IOException
{
int elapseTime = -1;
if( fileName == null || startFunct == null || endFunct == null )
return elapseTime;
BufferedReader br = null;
String currentLine = "";
try
{
br = new BufferedReader( new FileReader( fileName ) );
currentLine = br.readLine();
while( currentLine != null && !getFunctName(currentLine).equals(startFunct) )
{
currentLine = br.readLine();
}
}
catch( IOException e )
{
if( br != null )
{
br.close();
}
return -1;
}
int startCount = 1;
int endCount = 0;
int oddTime = getTime(currentLine);
int evenTime = 0;
int count = 1;
while( (currentLine = br.readLine()) != null && startCount != endCount )
{
if( getFunctName(currentLine).equals(startFunct) )
startCount++;
if( getFunctName(currentLine).equals(endFunct) )
endCount++;
count++;
if( count % 2 == 0 )
evenTime += getTime( currentLine );
else
oddTime += getTime( currentLine );
}
br.close();
if( startCount == endCount )
{
return evenTime - oddTime;
}
return -1;
}
public String getFunctName( String readLine )
{
if( readLine == null )
return null;
int index = readLine.indexOf(",");
if( index != -1 )
{
return readLine.substring(1, index);
}
return null;
}
public int getTime( String readLine )
{
if( readLine == null )
{
return -1;
}
int start = readLine.indexOf(",") + 1;
int end = readLine.indexOf(":", start);
if( start > 1 && end > start )
{
return Integer.parseInt(readLine.substring(start, end))*60 +
Integer.parseInt(readLine.substring(end + 1, readLine.length()-2));
}
return -1;
}
}
Simplest way is to use split. Runtime: O(m+n)
- icoderttc December 09, 2012