Advertisement
Guest User

Untitled

a guest
Nov 25th, 2011
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.78 KB | None | 0 0
  1. package labirinth
  2. import java.io._
  3. import java.util.Scanner
  4. import scala.annotation.tailrec
  5. object Main {
  6.   class TextFile(stream:InputStream) extends Iterable[String]{
  7.     val scanner = new Scanner(stream)
  8.     def iterator = new Iterator[String]{
  9.       def hasNext = scanner.hasNextLine
  10.       def next = scanner.nextLine
  11.     }
  12.   }
  13.   case class Point(i:Int, j:Int){
  14.     def +(that:Point) = Point(i+that.i,j+that.j)
  15.     override def toString = "["+i+","+j+"]"
  16.     def rotateClockWise = Point(j,-i)
  17.     def rotateCouterWise = Point(-j,i)
  18.   }
  19.   class Labirinth(i:InputStream){
  20.     val grid = new TextFile(i).map(x=>x.filter(_!=' ').toArray).toArray
  21.     val max = Point(grid.size-1,grid(0).size-1)
  22.     val start = grid.zipWithIndex.foldLeft(Point(-1,-1)){(acc,line)=>
  23.       if(line._1.contains('X')) Point(line._2, line._1.indexOf('X')) else acc
  24.     }
  25.     def directionHelper(value:Int, maxValue:Int, fromZero:Int):Int = value match{
  26.       case 0 => fromZero
  27.       case x if x==maxValue => -fromZero
  28.       case _ => 0
  29.     }
  30.     val startDirection = Point(directionHelper(start.i,max.i,-1),directionHelper(start.j,max.j,1))
  31.     def canGo(position:Point) = grid(position.i)(position.j)=='.'
  32.     @tailrec
  33.     private def go(position:Point, direction:Point,way:List[Point]):List[Point] = position match {
  34.       case q@(Point(0,_) | Point(_,0) | Point(max.i,_) | Point(_,max.j)) if q!=start => way
  35.       case _ => {
  36.           var newDirection = direction.rotateClockWise
  37.           while (!canGo(position+newDirection)) newDirection = newDirection.rotateCouterWise
  38.           go(position+newDirection, newDirection, position::way)
  39.       }
  40.     }
  41.     def run = println(go(start, startDirection, List()))
  42.   }
  43.   def main(args: Array[String])= new Labirinth(new FileInputStream("input.txt")).run
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement