This repository has been archived by the owner on Nov 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdimacs.go
85 lines (78 loc) · 1.5 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
package main
import (
"bufio"
"fmt"
"strconv"
"strings"
)
func readClause(line string, s *Solver) (lits []Lit, err error) {
values := strings.Fields(line)
if values[len(values)-1] != "0" {
return nil, fmt.Errorf("PARSE ERROR! The end of clause is not 0: %s", line)
}
for i := 0; i < len(values)-1; i++ {
parsedValue, err := strconv.Atoi(values[i])
if err != nil {
return nil, err
}
if parsedValue == 0 {
return nil, fmt.Errorf("PARSE ERROR! The format of cnf input is worng")
}
value := parsedValue
neg := false
if parsedValue > 0 {
value--
} else {
neg = true
value *= -1
value--
}
for value >= s.NumVars() {
s.NewVar()
}
lit := NewLit(Var(value), neg)
lits = append(lits, *lit)
}
return lits, nil
}
func parseDimacs(in *bufio.Scanner, s *Solver) (err error) {
vars := 0
clauses := 0
cnt := 0
for in.Scan() {
line := in.Text()
//skip empty line
if len(line) == 0 {
continue
}
//skip comment
if strings.HasPrefix(line, "c") {
continue
}
if strings.HasPrefix(line, "p cnf") {
values := strings.Fields(line)
vars, err = strconv.Atoi(values[2])
if err != nil {
return err
}
clauses, err = strconv.Atoi(values[3])
if err != nil {
return err
}
} else {
cnt++
lits, err := readClause(line, s)
if err != nil {
return err
}
if lits != nil {
s.addClause(lits)
}
}
}
if cnt != clauses {
fmt.Printf("PARSE ERROR! wrong number of clause: %d %d", cnt, clauses)
}
_ = vars
return nil
}