Advertisement
Guest User

Przykładowy kod Scala

a guest
Jul 10th, 2014
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.98 KB | None | 0 0
  1. object WaterPouringProblem {
  2.  
  3.   def main(args: Array[String]) = println (new Pouring(Vector(2,9,3)).solution(8))
  4.  
  5.  
  6.   class Pouring(capac: Vector[Int]) {
  7.     type State = Vector[Int]
  8.     val initialState = capac map (_ => 0)
  9.  
  10.     trait Move {
  11.       def change(state: State): State;
  12.     }
  13.     case class Empty(glass: Int) extends Move {
  14.       def change(state: State): State =
  15.         state updated (glass, 0)
  16.     }
  17.     case class Fill(glass: Int) extends Move {
  18.       def change(state: State): State =
  19.         state updated (glass, capac(glass))
  20.     }
  21.     case class Pour(from: Int, to: Int) extends Move {
  22.       def change(state: State): State = {
  23.         val amount = state(from) min (capac(to) - state(to))
  24.         state updated (from, state(from) - amount) updated (to, state(to) + amount)
  25.       }
  26.     }
  27.  
  28.     val glasses = 0 until capac.length
  29.  
  30.     val moves =
  31.       (for (g <- glasses) yield Empty(g)) ++
  32.         (for (g <- glasses) yield Fill(g)) ++
  33.         (for (g1 <- glasses; g2 <- glasses if (g2 != g1)) yield Pour(g1, g2));
  34.  
  35.     class Path(history: List[Move], val finalState: State) {
  36.       def extend(move: Move) = new Path(move :: history, move.change(finalState))
  37.       override def toString =
  38.         (history.reverse mkString " -> ") + " => " + finalState
  39.     }
  40.     val initialPath = new Path(Nil, initialState);
  41.  
  42.     def from(paths: Set[Path], explored: Set[State]): Stream[Set[Path]] = {
  43.       if (paths.isEmpty) Stream.empty
  44.       else {
  45.         val more = for {
  46.           path <- paths
  47.           next <- moves map path.extend
  48.           if !explored.contains(next.finalState)
  49.         } yield next
  50.         paths #:: from(more, explored ++ more.map(_.finalState))
  51.       }
  52.     }
  53.  
  54.     val pathSets: Stream[Set[Path]] = from(Set(initialPath), Set(initialState));
  55.  
  56.     def solution(target: Int): Stream[Path] = {
  57.       for {
  58.         pathSet <- pathSets
  59.         path <- pathSet
  60.         if (path.finalState contains target)
  61.       } yield path
  62.     }
  63.   }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement