Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- class Program
- {
- static void Main()
- {
- var moves = Poisson(new[] { 3, 5, 8 }, new[] { 0, 0, 8 }, 4);
- if (moves == null)
- Console.WriteLine("No solution!");
- else
- foreach (var move in moves)
- Console.WriteLine("{0} --> {1}, quantity: {2}", move.Item1, move.Item2, move.Item3);
- }
- static List<Tuple<int, int, int>> Poisson(
- int[] max,
- int[] now,
- int goal, // d
- List<Tuple<int, int, int>> moves = null,
- HashSet<Tuple<int, int, int>> seen = null)
- {
- moves = moves ?? new List<Tuple<int, int, int>>();
- seen = seen ?? new HashSet<Tuple<int, int, int>>();
- // been here before?
- if (!seen.Add(Tuple.Create(now[0], now[1], now[2])))
- return null;
- // check for success
- for (int ii = 0; ii < now.Length; ++ii)
- if (now[ii] == goal)
- return moves;
- for (int from = 0; from < now.Length; ++from)
- for (int to = 0; to < now.Length; ++to)
- {
- if (from == to || now[from] == 0 || now[to] == max[to])
- continue;
- int qty = Math.Min(max[to] - now[to], now[from]);
- // pour from --> to
- now[to] += qty;
- now[from] -= qty;
- moves.Add(Tuple.Create(from, to, qty));
- if (Poisson(max, now, goal, moves, seen) != null)
- return moves;
- // revert move
- now[from] += qty;
- now[to] -= qty;
- moves.RemoveAt(moves.Count - 1);
- }
- // failed
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment