Advertisement
Guest User

Untitled

a guest
Sep 30th, 2014
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 12.77 KB | None | 0 0
  1. import java.io._
  2. import scala.collection.mutable.MutableList
  3. import sun.security.util.Length
  4. import com.sun.org.apache.xpath.internal.operations.Bool
  5. import com.sun.corba.se.spi.orbutil.fsm.Guard
  6.  
  7.  
  8. object Solver extends App {
  9.  
  10.     val inputdir = "E:\\dev\\input"; // Change to real input dir
  11.     val outputdir = "E:\\dev\\input"; // Change to real output dir
  12.    
  13.     val WHITE = 1;
  14.     val BLUE = 2;
  15.     var long:Long=0;
  16.  
  17.     import java.io.File;
  18.    
  19.     val dir = new File(inputdir);
  20.     for(f<-dir.listFiles()){
  21.       solveSkySkraper(f)
  22.     }
  23.    
  24.     // A class representing a single square of the puzzle.
  25.     class Square (xNumber:Int, yNumber:Int, values:List[Int]=List(1,2), solved:Boolean=false) {
  26.       val x = xNumber;
  27.       val y = yNumber;
  28.       val s = solved;
  29.       val possibleValues = values;
  30.      
  31.       /**
  32.        *  Sends in a solution, and removes all other solution to that square.
  33.        */
  34.       def setValue(solution:Int, square:Square):Square = {
  35.         val solved =  new Square(square.x,square.y,List(solution), true);
  36.         return solved;
  37.       }
  38.      
  39.       /**
  40.        *  Removes a given value from the list of possible values.
  41.        */
  42.       def removeValue(wrongSolution:Int, square:Square):Square = {
  43.         if(wrongSolution == 1) {
  44.           return setValue(2, square);
  45.         }
  46.         else {
  47.           return setValue(1, square);
  48.         }
  49.       }
  50.         override def toString ():String={
  51.           return possibleValues.toString;
  52.         }
  53.     }
  54.    
  55.    
  56.    
  57.     def solveSkySkraper(f:File):Unit = {
  58.       println(f.getName())
  59.       val lines = scala.io.Source.fromFile(f).mkString.split("\n")
  60.       val numPuzzles:Int = lines(0).trim().toInt;
  61.       // Keeps this two non functional.
  62.       var numRows:Int = lines(1).trim().toInt;
  63.       var currLine:Int = 2;
  64.      
  65.       var list = MutableList[String]();
  66.  
  67.       for( a <- 1 to numPuzzles ){
  68.         for ( a <- 1 to numRows){
  69.             list +=lines(currLine);
  70.             currLine+=1;
  71.             }
  72.         if(a != numPuzzles) {
  73.         println("Finished parsing game, going on to start solving...");
  74.        
  75.         // SOLVE
  76.         translateRaw(list);
  77.         // Continue if there are more games in the file...
  78.         numRows = lines(currLine).trim().toInt+1;
  79.         currLine+=1;
  80.         list.clear();
  81.         }
  82.         else {
  83.          // println("This was the last game in file, solving it...");
  84.          //list.foreach(println)
  85.         var listSq = translateRaw(list);
  86.             val t0 = System.nanoTime()
  87.         SolvePuzzles(listSq);
  88.              val t1 = System.nanoTime()
  89.              println();
  90.         println("Elapsed time: " + (t1 - t0)/1000000 + "ms")
  91.  
  92.         }
  93.      }
  94.      
  95.       /*
  96.        *  Translates the raw list, to a valid format of Square objects.
  97.        */
  98.       def translateRaw (unparsed:MutableList[String]):MutableList[Square] = {
  99.         var list = MutableList[Square]();
  100.        var row = 0;
  101.         for(x<-unparsed) {
  102.            for(a<-0 to x.size-1) {
  103.  
  104.              val char = x.charAt(a).toString;
  105.               if(char == ".") {
  106.                 var sq = (new Square(a,row,List(1,2),false));
  107.                 list+= sq;
  108.               }
  109.               if(char == "w") {
  110.                 var sq = (new Square(a,row,List(1),true));
  111.                 list+= sq;
  112.               }
  113.               if(char == "b") {
  114.                var sq = (new Square(a,row,List(2),true));
  115.                list+= sq;
  116.                  }
  117.            }
  118.             row+=1;
  119.  
  120.         }
  121.        
  122.         return list;
  123.       }
  124.      
  125.       def SolvePuzzles(list:MutableList[Square]) {
  126.  
  127.       var newList = list;
  128.  
  129.       var listCopy = newList;
  130.  
  131.      newList = checkForForcedSolution(newList);
  132.  
  133.       newList = checkForLineAndColumns(newList);
  134.       var hello = bruteForcer(newList);
  135.       listCopy = hello._1;
  136.     var b  = hello._2;
  137.     println (b);
  138.  
  139.    
  140.         printIt(listCopy);
  141.         println();
  142.         println("time spent replacing squares: " + long/1000000 + "ms")
  143.  
  144.       }
  145.      
  146.       def bruteForcer (list:MutableList[Square]):(MutableList[Square],Boolean) = {
  147.         var prevSave =  list;
  148.        prevSave = checkForForcedSolution(prevSave);
  149.        prevSave = checkForLineAndColumns(prevSave);
  150.         var next = getNextUnsolved(list);
  151.         var osquare = next._1 ;
  152.         var square = osquare;
  153.         var continue = next._2;
  154.      
  155.        
  156.         if(!continue) {
  157.           println("stopping");
  158.         return (prevSave, true)  
  159.         }
  160.         //checks 1
  161.        
  162.          
  163.  
  164.              
  165.        
  166.         square = square.setValue(1, square);
  167.                var t0 = System.nanoTime()
  168.         prevSave = replaceSquare(square, prevSave);
  169.                var t1 = System.nanoTime()
  170.                long= long+(t1-t0);
  171.         if(checkIfValid(prevSave))  {
  172.         var res = bruteForcer(prevSave) //
  173.         if (res._2){
  174.           prevSave=res._1;
  175.           return (prevSave,true);}
  176.         }
  177.         //checks 2
  178.         square = square.setValue(2, square);
  179.         var t3 = System.nanoTime()
  180.         prevSave = replaceSquare(square, prevSave);
  181.         var t4 = System.nanoTime()
  182.         long= long+(t4-t3);
  183.         if(checkIfValid(prevSave))  {
  184.         var res = bruteForcer(prevSave) //
  185.         if (res._2){
  186.           prevSave=res._1;
  187.           return (prevSave,true);}
  188.         }
  189.        
  190.      // prevSave = replaceSquare(osquare,prevSave);
  191.       return (prevSave,false);
  192.       }
  193.      
  194.       /**
  195.        *  Gives you the next square that is unsolved, returns false if
  196.        *  everything is solved.
  197.        */
  198.       def getNextUnsolved (list:MutableList[Square]):(Square, Boolean) = {
  199.         for( a <- 0 to math.sqrt(list.length).toInt-1){
  200.           for( b <- 0 to math.sqrt(list.length).toInt-1){
  201.             if(!getSquare(b, a, list).s) {
  202.               return (getSquare(b, a, list),true);
  203.             }
  204.           }
  205.         }
  206.        
  207.         return (getSquare(0, 0, list),false)
  208.       }
  209.      
  210.       def checkIfValid(list:MutableList[Square]):Boolean = {
  211.          for( b <- 0 to math.sqrt(list.length).toInt-1){
  212.             var column = getAllFromX(b, list);
  213.             var line = getAllFromY(b, list);
  214.             if(!(checkIfLineIsValid(column))) {
  215.               return false;
  216.             }
  217.             if(!(checkIfLineIsValid(line))) {
  218.               return false;
  219.             }
  220.           }
  221.          return true;
  222.       }
  223.      
  224.       def checkIfLineIsValid (list:MutableList[Square]):Boolean = {
  225.         var b = 0;
  226.         var w = 0;
  227.         var w_1 = 0;
  228.         var b_1 = 0;
  229.        
  230.         for (a<- list) {
  231.          
  232.           if(a.s) {
  233.             // Check for three in a row..
  234.             if(a.possibleValues(0) == WHITE ) {
  235.              w = w+1
  236.              b = 0;
  237.              w_1 = w_1+1;
  238.            }
  239.            else {
  240.              b = b+1;
  241.              w = 0;
  242.              b_1 = b_1+1;
  243.            }
  244.           }
  245.           else {
  246.             b=0;
  247.             w=0;
  248.           }
  249.           if(b == 3 || w == 3 || w_1 > list.length/2 || b_1 > list.length/2) {
  250.             return false;
  251.           }
  252.          
  253.  
  254.          
  255.          
  256.           // Check for equal amount in lines..
  257.          
  258.         }
  259.         return true;
  260.       }
  261.      
  262.       def compareResults(list:MutableList[Square],list2:MutableList[Square]):Boolean = {
  263.         var numberOfSolved1 = 0;
  264.         var numberOfSolved2 = 0;
  265.         for (a<-list) {
  266.           if(a.s)  {
  267.           numberOfSolved1 = numberOfSolved1 +1;        
  268.           }
  269.         }
  270.         for(a<- list2) {
  271.         if(a.s) {
  272.           numberOfSolved2 = numberOfSolved2 +1;
  273.         }
  274.         }
  275.        
  276.         if(numberOfSolved1 == numberOfSolved2) {
  277.           return true
  278.         }
  279.        
  280.         return false;
  281.       }
  282.      
  283.       def checkForForcedSolution(list:MutableList[Square]):MutableList[Square] = {
  284.         var newList = list;
  285.         for (a<-newList) {
  286.          newList = removeIfNotValid(a, newList);
  287.         }
  288.         return newList;
  289.       }
  290.      
  291.       def checkForLineAndColumns(list:MutableList[Square]):MutableList[Square] = {
  292.         var newList = list;
  293.        
  294.         for( b <- 0 to math.sqrt(list.length).toInt-1){
  295.             var column = getAllFromX(b, newList);
  296.             var line = getAllFromY(b, newList);
  297.             newList = lineCheck(line,newList);
  298.             newList = lineCheck(column,newList)
  299.           }
  300.        
  301.         return newList;
  302.       }
  303.      
  304.       def removeIfNotValid(square:Square, list:MutableList[Square]):MutableList[Square]={
  305.         var newList = list;
  306.         var tuple = isForced(square, list);
  307.         if(tuple._1){
  308.             if(tuple._2 == 1) {
  309.              var square_t = square.removeValue(1, square)
  310.              square_t.s == true;
  311.              newList =  replaceSquare(square_t, list);
  312.             }
  313.             else {
  314.               var square_t = square.removeValue(2, square)
  315.              square_t.s == true;
  316.              newList =  replaceSquare(square_t, list);
  317.             }
  318.           }
  319.          return newList;
  320.       }
  321.      
  322.       /**
  323.        *  Check a sqaure's x & y axis for even amounts of b&w.
  324.        */
  325.       def lineCheck(line:MutableList[Square], list:MutableList[Square]):MutableList[Square] = {
  326.         var solution = list;
  327.        
  328.         var white = 0;
  329.         var blue = 0;
  330.         // Check all line..
  331.         for(a<-line) {
  332.           if(a.s) {
  333.             if(a.possibleValues(0) == WHITE) {
  334.               white = white+1;
  335.             }
  336.             else {
  337.               blue = blue + 1;
  338.             }
  339.           }
  340.         }
  341.        
  342.         if((white == line.length/2) && !(blue == line.length/2)) {
  343.             for(a <- line) {
  344.               if(!a.s){
  345.                 var temp_s = a.setValue(BLUE , a);
  346.                 solution = replaceSquare(temp_s, solution);
  347.               }
  348.             }
  349.         }
  350.        
  351.          if((blue == line.length/2) && !(white == line.length/2)) {
  352.             for(a <- line) {
  353.                 if(!a.s){
  354.                     var temp_s = a.setValue(WHITE , a);
  355.                     solution = replaceSquare(temp_s, solution);
  356.                 }
  357.             }
  358.         }      
  359.         return solution;
  360.       }
  361.      
  362.       /**
  363.        *  Checks if a square is forced to a value, by the predefined known values.
  364.        *  This function checks two squares, in each direction.
  365.        */
  366.       def isForced (square:Square, list:MutableList[Square]):(Boolean, Int) = {
  367.         val x = square.x;
  368.         val y = square.y;
  369.        
  370.         // Checking left
  371.         if(checkForced(getSquare(x-1, y, list), getSquare(x-2, y-0, list))) {
  372.           return (true,getSquare(x-1, y, list).possibleValues(0));
  373.         }
  374.         // Checking down
  375.         else if(checkForced(getSquare(x, y+1, list), getSquare(x, y+2, list))) {
  376.         return (true,getSquare(x, y+1, list).possibleValues(0));
  377.  
  378.         }
  379.         // Checking right
  380.         else if(checkForced(getSquare(x+1, y, list), getSquare(x+2, y, list))) {
  381.         return (true,getSquare(x+1, y, list).possibleValues(0));
  382.  
  383.         }
  384.             // Checking up
  385.         else if(checkForced(getSquare(x, y-1, list), getSquare(x, y-2, list))) {
  386.  
  387.         return (true,getSquare(x, y-1, list).possibleValues(0));
  388.  
  389.         }
  390.         // Checking inner horizontal
  391.         else if(checkForced(getSquare(x-1, y, list), getSquare(x+1, y, list))) {
  392.  
  393.         return (true,getSquare(x-1, y, list).possibleValues(0));
  394.  
  395.         }
  396.         // Checking inner vertical
  397.         else if(checkForced(getSquare(x, y-1, list), getSquare(x, y+1, list))) {
  398.  
  399.         return (true,getSquare(x, y-1, list).possibleValues(0));
  400.  
  401.         }
  402.         return (false,1);
  403.       }
  404.      
  405.       /**
  406.        *  A subfunction for isForced(); checking if
  407.        *  two squares is equal to one another.
  408.        */
  409.       def checkForced(sq1:Square, sq2:Square):Boolean = {
  410.         if(sq1.possibleValues(0) == sq2.possibleValues(0) && (sq1.s && sq2.s)) {
  411.           return true;
  412.         }
  413.         else {
  414.           return false;
  415.         }
  416.       }
  417.      
  418.       /**
  419.        * Replace a given square in the solution list.
  420.        */
  421.       def replaceSquare(square:Square, list:MutableList[Square]):MutableList[Square] = {
  422.         var newList = MutableList[Square]();
  423.         for(a <- list) {
  424.           if(a.x == square.x  && a.y == square.y) {
  425.             newList += (new Square(square.x,square.y,square.possibleValues,square.s));
  426.           }
  427.           else {
  428.           newList += a;        
  429.           }
  430.         }
  431.         return newList;
  432.       }
  433.      
  434.       def printIt(list:MutableList[Square]):Unit = {
  435.         var a = 0;
  436.         var b = 0;
  437.         for( a <- 0 to math.sqrt(list.length).toInt-1){
  438.             println();
  439.           for( b <- 0 to math.sqrt(list.length).toInt-1){
  440.             if(getSquare(b, a, list).s) {
  441.               print("("+getSquare(b, a, list).possibleValues(0)+")");
  442.             }
  443.             else {
  444.               print("(n)");
  445.             }
  446.            
  447.            
  448.           }
  449.         }
  450.       }
  451.      
  452.       def getSquare(x:Int,y:Int, allSquares:MutableList[Square]):Square = {
  453.         if(x<0 || y < 0 || x > math.sqrt(allSquares.length)-1 || y > math.sqrt(allSquares.length)-1) {
  454.           return  new Square(0,0,List(1,2),false)
  455.         }
  456.         else {
  457.          return allSquares.filter(_.x==x).filter(_.y==y)(0)
  458.         }
  459.     }
  460.      
  461.       def getAllFromX(i:Int, list:MutableList[Square]):MutableList[Square] = {
  462.             return list.filter(_.x == i)
  463.     }
  464.  
  465.       def getAllFromY(i:Int, list:MutableList[Square]):MutableList[Square] = {
  466.             return list.filter(_.y == i)
  467.     }
  468.  
  469.      
  470.    
  471.  
  472.      
  473.       /*
  474.       var out = new PrintWriter( new File(outputdir+"\\"+f.getName()) , "UTF-8")
  475.      out.print(numPuzzles + "\n")
  476.      
  477.       var sol = ""
  478.       out.print("6\n") //Fake solution
  479.       out.print("wwbwbb\n")
  480.       out.print("bbwbww\n")
  481.       out.print("wbwbwb\n")
  482.       out.print("wwbwbb\n")
  483.       out.print("bbwbww\n")
  484.       out.print("bwbwbw\n")
  485.       out.print("8\n")
  486.       out.print("bwwbwwbb\n")
  487.       out.print("bwbwbwbw\n")
  488.       out.print("wbwwbbwb\n")
  489.       out.print("wwbbwbbw\n")
  490.       out.print("bbwwbwwb\n")
  491.       out.print("wwbbwbbw\n")
  492.       out.print("bbwbwbww\n")
  493.       out.print("wbbwbwwb\n")
  494.  
  495.       out.close();
  496.     */
  497.    
  498.     }
  499.    
  500.  
  501.    
  502. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement