Advertisement
Guest User

Untitled

a guest
Dec 5th, 2016
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.13 KB | None | 0 0
  1. def kColoringSAT(g: Graph, k: Int): Option[Map[Int,Int]] = {
  2.     // Imports needed to use the SAT4J
  3.     import org.sat4j.minisat.SolverFactory
  4.     import org.sat4j.core.VecInt
  5.  
  6.     require(g != null && g.nofVertices > 0)
  7.     require(k >= 1 & k <= 64)
  8.     val N = g.nofVertices
  9.  
  10.     // Handle special cases separately
  11.     if(k == 0) {
  12.       if(g.nofVertices == 0) return Some(Map[Int,Int]())
  13.       else return None
  14.     }
  15.     if(k == 1) {
  16.       if((0 until N).forall(v => g.neighbours(v).isEmpty))
  17.         return Some((0 until N).map({case v => (v,0)}).toMap)
  18.       return None
  19.     }
  20.    
  21.     def vertexColorToVar(vertex: Int, color: Int): Int = {
  22.       require(0 <= vertex && vertex < N)
  23.       require(0 <= color && color < k)
  24.       1 + vertex + color
  25.     }
  26.  
  27.     // Create the SAT solver instance
  28.     val solver = SolverFactory.newDefault()
  29.     // Tell the solver how many Boolean variables there will be
  30.     solver.newVar(N*k)
  31.    
  32.     // Create the instance, call the SAT solver and interpret the result
  33.    
  34.     for(vertex <- 0 until N) {
  35.       //The vertex has at least one color
  36.       val clause = (0 until k).map(vertexColorToVar(vertex,_)).toArray
  37.       solver.addClause(new VecInt(clause))
  38.      
  39.       //The vertex has at most one color
  40.       for(c1 <- 0 until k) {
  41.         for(c2 <- 0 until k) {
  42.           val clause = Array[Int](-vertexColorToVar(vertex, c1),
  43.                                   -vertexColorToVar(vertex, c2))
  44.           solver.addClause(new VecInt(clause))
  45.         }
  46.       }
  47.      
  48.       //The nodes for every edge has different colors.
  49.       for(c <- 0 until k) {
  50.         for(n <- g.neighbours(vertex)) {
  51.           val clause = Array[Int](-vertexColorToVar(vertex, c),
  52.                                   -vertexColorToVar(n, c))
  53.           solver.addClause(new VecInt(clause))
  54.         }
  55.       }
  56.     }
  57.    
  58.    
  59.     if(solver.isSatisfiable()) {
  60.       var result = HashMap[Int, Int]()
  61.       for(v <- 0 until N; c <- 0 until k) {
  62.         if(solver.model(vertexColorToVar(v, c))) {
  63.           result += ((v, c))
  64.         }
  65.       }
  66.       Some(result.toMap)
  67.     } else None
  68.    
  69.    
  70.    
  71.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement