|
| 1 | +class Pouring(capacity: Vector[Int]) with |
| 2 | + type Glass = Int |
| 3 | + type Content = Vector[Int] |
| 4 | + |
| 5 | + enum Move with |
| 6 | + def apply(content: Content): Content = this match |
| 7 | + case Empty(g) => content.updated(g, 0) |
| 8 | + case Fill(g) => content.updated(g, capacity(g)) |
| 9 | + case Pour(from, to) => |
| 10 | + val amount = content(from) min (capacity(to) - content(to)) |
| 11 | + def (s: Content) adjust (g: Glass, delta: Int) = s.updated(g, s(g) + delta) |
| 12 | + content.adjust(from, -amount).adjust(to, amount) |
| 13 | + |
| 14 | + case Empty(glass: Glass) |
| 15 | + case Fill(glass: Glass) |
| 16 | + case Pour(from: Glass, to: Glass) |
| 17 | + end Move |
| 18 | + |
| 19 | + val moves = |
| 20 | + val glasses = 0 until capacity.length |
| 21 | + (for g <- glasses yield Move.Empty(g)) |
| 22 | + ++ (for g <- glasses yield Move.Fill(g)) |
| 23 | + ++ (for g1 <- glasses; g2 <- glasses if g1 != g2 yield Move.Pour(g1, g2)) |
| 24 | + |
| 25 | + class Path(history: List[Move], val endContent: Content) with |
| 26 | + def extend(move: Move) = Path(move :: history, move(endContent)) |
| 27 | + override def toString = s"${history.reverse.mkString(" ")} --> $endContent" |
| 28 | + end Path |
| 29 | + |
| 30 | + val initialContent: Content = capacity.map(x => 0) |
| 31 | + val initialPath = Path(Nil, initialContent) |
| 32 | + |
| 33 | + def from(paths: Set[Path], explored: Set[Content]): LazyList[Set[Path]] = |
| 34 | + if paths.isEmpty then LazyList.empty |
| 35 | + else |
| 36 | + val extensions = |
| 37 | + for |
| 38 | + path <- paths |
| 39 | + move <- moves |
| 40 | + next = path.extend(move) |
| 41 | + if !explored.contains(next.endContent) |
| 42 | + yield next |
| 43 | + paths #:: from(extensions, explored ++ extensions.map(_.endContent)) |
| 44 | + |
| 45 | + def solutions(target: Int): LazyList[Path] = |
| 46 | + for |
| 47 | + paths <- from(Set(initialPath), Set(initialContent)) |
| 48 | + path <- paths |
| 49 | + if path.endContent.contains(target) |
| 50 | + yield path |
| 51 | +end Pouring |
| 52 | + |
| 53 | +@main def Test = |
| 54 | + val problem = Pouring(Vector(4, 7)) |
| 55 | + println(problem.moves) |
| 56 | + println(problem.solutions(6).head) |
0 commit comments