-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdimacs.go
117 lines (86 loc) · 2.11 KB
/
dimacs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"bufio"
"errors"
"os"
"strconv"
"strings"
)
func readDimacsCnfFile(path string) (*Problem, error) {
file, err := os.Open(path)
defer file.Close()
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(file)
numVars, numClauses := 0, 0
problem := NewProblem()
// Read header
for scanner.Scan() {
if scanner.Err() != nil {
return nil, err
}
line := scanner.Text()
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "p ") && strings.Fields(line)[1] == "cnf" {
// Get the ammount of variables
numVars, err = strconv.Atoi(strings.Fields(line)[2])
if err != nil {
return nil, errors.New("unknown line type '" + line + "'")
}
// And constraints
numClauses, err = strconv.Atoi(strings.Fields(line)[3])
if err != nil {
return nil, errors.New("unknown line type '" + line + "'")
}
// Done reading header
break
} else if strings.HasPrefix(line, "c ") || line == "c" || line == "" {
// Skip comments and empty lines
} else {
return nil, errors.New("unknown line type '" + line + "'")
}
}
// Read clauses
readClauses, line := 0, ""
for scanner.Scan() {
if scanner.Err() != nil {
return nil, err
}
segment := scanner.Text()
// Skip comments
if strings.HasPrefix(segment, "c") {
continue
}
line += " " + segment
line = strings.TrimSpace(line)
if !strings.HasSuffix(line, " 0") {
continue
}
line = strings.TrimSpace(strings.TrimSuffix(line, " 0"))
if line == "%" {
// End of file marker, seen in some files
break
}
readClauses++
if readClauses > numClauses {
return nil, errors.New("too many clauses in file")
}
clause := map[int]bool{}
for _, v := range strings.Fields(line) {
vr, err := strconv.Atoi(v)
if err != nil || vr > numVars || vr == 0 {
return nil, errors.New("invalid constraint " + line)
}
clause[vr] = true
}
// Add clause and reset line
problem.AddClause(clause)
line = ""
}
// Check if the ammount of clauses is correct
if readClauses != numClauses {
return nil, errors.New("too few clauses in file")
}
return problem, nil
}