patternjavaMinor
Parser for CNF formulas
Viewed 0 times
parsercnfforformulas
Problem
I have a parser for CNF formulas in Dimacs format, which is very slow. Any suggestion on how to improve its speed? I did some profiling and I might have to replace
A possible input for the parser is:
The code:
```
/**
* Parses a stream for a CNF instance.
*
* @param source input stream
* @return read skeleton
* @throws ParseException if stream contains an invalid instance
*/
private static Skeleton parseStream(final InputStream source)
throws IOException, ParseException {
Scanner scanner = new Scanner(source);
// Skip comments
try {
String token = scanner.next();
while (token.equals("c")) {
scanner.nextLine();
token = scanner.next();
}
if (!token.equals("p")) {
throw new ParseException(
"Excepted 'p', but '" + token + "' was found");
}
} catch (NoSuchElementException e) {
throw new ParseException("Header not found");
}
// Reads header
int numVariables, numClauses;
try {
String cnf = scanner.
Scanner. Is there anything faster?A possible input for the parser is:
c A sample .cnf file.
p cnf 3 2
1 -3 0
2 3 -1 0The code:
```
/**
* Parses a stream for a CNF instance.
*
* @param source input stream
* @return read skeleton
* @throws ParseException if stream contains an invalid instance
*/
private static Skeleton parseStream(final InputStream source)
throws IOException, ParseException {
Scanner scanner = new Scanner(source);
// Skip comments
try {
String token = scanner.next();
while (token.equals("c")) {
scanner.nextLine();
token = scanner.next();
}
if (!token.equals("p")) {
throw new ParseException(
"Excepted 'p', but '" + token + "' was found");
}
} catch (NoSuchElementException e) {
throw new ParseException("Header not found");
}
// Reads header
int numVariables, numClauses;
try {
String cnf = scanner.
Solution
Use a
BufferedInputStream to speed up the disk access. If that's not enough, you can read the file line-by-line and use split() to break it into individual numbers.Context
StackExchange Code Review Q#784, answer score: 7
Revisions (0)
No revisions yet.