public void should_have_correct_number_of_unique_solutions(int n, int numSolutions)
        {
            var solver = new Solver(n);
              var results = solver.Solve();

              Assert.AreEqual(numSolutions, results.Count);
        }
Exemplo n.º 2
0
 public FltGenerate( Solver solver, FltVar[] list, FltVarSelector.Select select, FltSearch search )
     : base(solver)
 {
     m_FltVarList		= list;
     m_SelectVar			= select;
     m_Search			= search;
 }
Exemplo n.º 3
0
 public FltGenerate( Solver solver, FltVar[] list )
     : base(solver)
 {
     m_FltVarList		= list;
     m_SelectVar			= FltVarSelector.CardinalityMin;
     m_Search			= new FltSearchDichotomize();
 }
Exemplo n.º 4
0
    public static void Main(String[] args)
    {
        String problem = "ft10";
        long timeout = 1000 * 60 * 10;
        String[] solverNames = new String[] { "sa", "ibb", "taboo" };
        int i = 0;
        if (i < args.Length)
            problem = args[i++];
        if (i < args.Length)
            timeout = Int32.Parse(args[i++]) * 1000;
        if (i < args.Length)
        {
            solverNames = new String[args.Length - i];
            int j = 0;
            for (; i < args.Length; i++)
            {
                solverNames[j++] = args[i];
            }
        }
        Network network = (new JSSPProblem(problem)).network();
        if (network == null)
            return;
        //int opt = Solver.MINIMIZE | Solver.BETTER;
        int opt = Solver.Default;
        Solver[] solvers = new Solver[solverNames.Length];
        for (i = 0; i < solvers.Length; i++)
        {
            String name = solverNames[i];
            if (name.Equals("sa"))
            {
                solvers[i] = new SimulatedAnneallingSearch((Network)network.Clone(), opt, name);
            }
            else if (name.Equals("ibb"))
            {
                solvers[i] = new IterativeBranchAndBoundSearch((Network)network.Clone(), opt, name);
            }
            else if (name.Equals("taboo") || name.Equals("tabu"))
            {
                solvers[i] = new TabooSearch((Network)network.Clone(), opt, name);
            }
            else if (name.Equals("rw"))
            {
                solvers[i] = new LocalSearch((Network)network.Clone(), opt, name);
            }
            else
            {
                Console.Out.WriteLine("Unknown solver name " + name);
                solvers[i] = null;
            }
        }
        Solver all = new ParallelSolver(solvers);

        //Monitor monitor = new Monitor();
         //monitor.setX(0, (int)(timeout/1000));
        //all.setMonitor(monitor);
        //SolutionHandler sh=null;
        Solution solution = all.FindBest(timeout);
        Console.Out.WriteLine(solution);
        Console.In.ReadLine();
    }
Exemplo n.º 5
0
    public static int Main()
    {
        for ( ; ; )
        {
            int n = int.Parse(ReadLine());

            if (n == 0) break;

            IList<string> stopWords =
                Enumerable.Range(0, n)
                .Select(_ => ReadLine().ToLowerInvariant())
                .ToArray();

            var testCases =
                Enumerable.Range(0, int.MaxValue)
                .Select(_ => ReadLine().ToLowerInvariant())
                .TakeWhile(s => s != null && s != "last case")
                .Select(s => s.Split(new[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries))
                .Select(words => new { Acronym = words[0], Definition = words.Skip(1).Except(stopWords) })
                .ToArray();

            foreach (var testCase in testCases)
            {
                int solution = new Solver(testCase.Acronym, testCase.Definition).Solve();

                if (solution == 0)
                    WriteLine($"{testCase.Acronym.ToUpperInvariant()} is not a valid abbreviation");
                else
                    WriteLine($"{testCase.Acronym.ToUpperInvariant()} can be formed in {solution} ways");
            }
        }
         
        return 0;
    }
Exemplo n.º 6
0
        public void Test_no_solution()
        {
            var value = 4;
            var capacities = new[] { 3, 5 };

            var pouringGeneratorFactory = MockRepository.GenerateStrictMock<IPouringGeneratorFactory>();
            var pouringGenerator = MockRepository.GenerateStrictMock<IPouringGenerator>();

            var solver = new Solver(
                pouringGeneratorFactory
            );

            pouringGeneratorFactory
                .Expect(f => f.Create(capacities.Length))
                .Return(pouringGenerator);

            pouringGenerator
                .Stub(g => g.GetNextGeneration(null))
                .IgnoreArguments()
                .Return(Enumerable.Empty<Pouring>());

            var solutions = solver
                .SolutionSequence(value, capacities)
                .ToArray();

            Assert.AreEqual(0, solutions.Length);
        }
  /**
   *
   * A simple propagator for modulo constraint.
   *
   * This implementation is based on the ECLiPSe version
   * mentioned in "A Modulo propagator for ECLiPSE"
   * http://www.hakank.org/constraint_programming_blog/2010/05/a_modulo_propagator_for_eclips.html
   * The ECLiPSe Prolog source code:
   * http://www.hakank.org/eclipse/modulo_propagator.ecl
   *
   */
  public static void MyMod(Solver solver, IntVar x, IntVar y, IntVar r) {

    long lbx = x.Min();
    long ubx = x.Max();
    long ubx_neg = -ubx;
    long lbx_neg = -lbx;
    int min_x = (int)Math.Min(lbx, ubx_neg);
    int max_x = (int)Math.Max(ubx, lbx_neg);

    IntVar d = solver.MakeIntVar(min_x, max_x, "d");

    // r >= 0
    solver.Add(r >= 0);

    // x*r >= 0
    solver.Add( x*r >= 0);

    // -abs(y) < r
    solver.Add(-y.Abs() < r);

    // r < abs(y)
    solver.Add(r < y.Abs());

    // min_x <= d, i.e. d > min_x
    solver.Add(d > min_x);

    // d <= max_x
    solver.Add(d <= max_x);

    // x == y*d+r
    solver.Add(x - (y*d + r) == 0);

  }
Exemplo n.º 8
0
  public static void minus(Solver solver, 
                           IntVar x, 
                           IntVar y, 
                           IntVar z) 
 {
   solver.Add(z == (x - y).Abs());
 }
Exemplo n.º 9
0
  /**
   *
   * Secret Santa problem in Google CP Solver.
   *
   * From Ruby Quiz Secret Santa
   * http://www.rubyquiz.com/quiz2.html
   * """
   * Honoring a long standing tradition started by my wife's dad, my friends
   * all play a Secret Santa game around Christmas time. We draw names and
   * spend a week sneaking that person gifts and clues to our identity. On the
   * last night of the game, we get together, have dinner, share stories, and,
   * most importantly, try to guess who our Secret Santa was. It's a crazily
   * fun way to enjoy each other's company during the holidays.
   *
   * To choose Santas, we use to draw names out of a hat. This system was
   * tedious, prone to many 'Wait, I got myself...' problems. This year, we
   * made a change to the rules that further complicated picking and we knew
   * the hat draw would not stand up to the challenge. Naturally, to solve
   * this problem, I scripted the process. Since that turned out to be more
   * interesting than I had expected, I decided to share.
   *
   * This weeks Ruby Quiz is to implement a Secret Santa selection script.
   * *  Your script will be fed a list of names on STDIN.
   * ...
   * Your script should then choose a Secret Santa for every name in the list.
   * Obviously, a person cannot be their own Secret Santa. In addition, my friends
   * no longer allow people in the same family to be Santas for each other and your
   * script should take this into account.
   * """
   *
   *  Comment: This model skips the file input and mail parts. We
   *        assume that the friends are identified with a number from 1..n,
   *        and the families is identified with a number 1..num_families.
   *
   * Also see http://www.hakank.org/or-tools/secret_santa.py 
   * Also see http://www.hakank.org/or-tools/secret_santa2.cs 
   *
   */
  private static void Solve()
  {

    Solver solver = new Solver("SecretSanta");

    int[] family = {1,1,1,1, 2, 3,3,3,3,3, 4,4};
    int n = family.Length;

    Console.WriteLine("n = {0}", n);

    IEnumerable<int> RANGE = Enumerable.Range(0, n);

    //
    // Decision variables
    //
    IntVar[] x = solver.MakeIntVarArray(n, 0, n-1, "x");


    //
    // Constraints
    //
    solver.Add(x.AllDifferent());

    // Can't be one own"s Secret Santa
    // (i.e. ensure that there are no fix-point in the array.)
    foreach(int i in RANGE) {
      solver.Add(x[i] != i);
    }


    // No Secret Santa to a person in the same family
    foreach(int i in RANGE) {
      solver.Add(solver.MakeIntConst(family[i]) != family.Element(x[i]));
    }

    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(x,
                                          Solver.INT_VAR_SIMPLE,
                                          Solver.INT_VALUE_SIMPLE);

    solver.NewSearch(db);

    while (solver.NextSolution()) {
      Console.Write("x:  ");
      foreach(int i in RANGE) {
        Console.Write(x[i].Value() + " ");
      }
      Console.WriteLine();
    }

    Console.WriteLine("\nSolutions: {0}", solver.Solutions());
    Console.WriteLine("WallTime: {0}ms", solver.WallTime());
    Console.WriteLine("Failures: {0}", solver.Failures());
    Console.WriteLine("Branches: {0} ", solver.Branches());

    solver.EndSearch();

  }
Exemplo n.º 10
0
 static void TestVarOperator()
 {
   Console.WriteLine("Running TestVarOperator");
   Solver solver = new Solver("TestVarOperator",
                              Solver.CLP_LINEAR_PROGRAMMING);
   Variable x = solver.MakeNumVar(0.0, 100.0, "x");
   Constraint ct1 = solver.Add(x >= 1);
   Constraint ct2 = solver.Add(x <= 1);
   Constraint ct3 = solver.Add(x == 1);
   Constraint ct4 = solver.Add(1 >= x);
   Constraint ct5 = solver.Add(1 <= x);
   Constraint ct6 = solver.Add(1 == x);
   CheckDoubleEq(ct1.GetCoefficient(x), 1.0, "test1");
   CheckDoubleEq(ct2.GetCoefficient(x), 1.0, "test2");
   CheckDoubleEq(ct3.GetCoefficient(x), 1.0, "test3");
   CheckDoubleEq(ct4.GetCoefficient(x), 1.0, "test4");
   CheckDoubleEq(ct5.GetCoefficient(x), 1.0, "test5");
   CheckDoubleEq(ct6.GetCoefficient(x), 1.0, "test6");
   CheckDoubleEq(ct1.Lb(), 1.0, "test7");
   CheckDoubleEq(ct1.Ub(), double.PositiveInfinity, "test8");
   CheckDoubleEq(ct2.Lb(), double.NegativeInfinity, "test9");
   CheckDoubleEq(ct2.Ub(), 1.0, "test10");
   CheckDoubleEq(ct3.Lb(), 1.0, "test11");
   CheckDoubleEq(ct3.Ub(), 1.0, "test12");
   CheckDoubleEq(ct4.Lb(), double.NegativeInfinity, "test13");
   CheckDoubleEq(ct4.Ub(), 1.0, "test14");
   CheckDoubleEq(ct5.Lb(), 1.0, "test15");
   CheckDoubleEq(ct5.Ub(), double.PositiveInfinity, "test16");
   CheckDoubleEq(ct6.Lb(), 1.0, "test17");
   CheckDoubleEq(ct6.Ub(), 1.0, "test18");
 }
        public void SolveBackPackProblemWith16RandomItems()
        {
            const int tests = 10;

            double bfFitness = 0.0;
            double gsFitness = 0.0;

            for (int n = 0; n < tests; n++)
            {
                var backPack = new BackPack(2000);
                var items = BackPackEnvironmentTest.RandomItems(16, backPack.Volume, 200);

                var environment = new BackPackEnvironment(backPack, items, 100);

                var solver = new Solver<BackPackIndividual>(environment);
                solver.Start(() => solver.CurrentGeneration > 10);

                var bf = BruteForce(environment);
                var gs = solver.CurrentOptimum;

                Console.WriteLine(environment.RateFitness(bf));
                Console.WriteLine(environment.RateFitness(gs));

                bfFitness += environment.RateFitness(bf);
                gsFitness += environment.RateFitness(gs);
            }
            // Should be atleast 90% of BF'ed fitness
            Console.WriteLine(gsFitness / bfFitness);
            Assert.IsTrue(bfFitness * 0.9 
                <= gsFitness);

        }
Exemplo n.º 12
0
        public void FillCellWithIntersectionOfKey()
        {
            IList<Line> columns = new List<Line>
                {
                    new Line( new List<Clue>() ),
                    new Line( new List<Clue>{new Clue( 2 )}),
                    new Line( new List<Clue>{new Clue( 3 )}),
                    new Line( new List<Clue>{new Clue( 1 )}),
                    new Line( new List<Clue>() )
                };

            IList<Line> rows = new List<Line>
                {
                    new Line( new List<Clue>() ),
                    new Line( new List<Clue>{new Clue( 2 )}),
                    new Line( new List<Clue>{new Clue( 3 )}),
                    new Line( new List<Clue>{new Clue( 1 )}),
                    new Line( new List<Clue>() )
                };
            var newField = new Field( columns, rows );

            var solver = new Solver( columns, rows );

            bool res =  solver.CheckFilled( newField.Cells[2, 2] );

            Assert.AreEqual( res, true );

            res = solver.CheckFilled( newField.Cells[1, 2] );

            Assert.AreEqual( res, false );
        }
Exemplo n.º 13
0
        public void NotResolveEmptyPosition()
        {
            Position position = new Position();
            Solver solver = new Solver();

            Assert.IsNull(solver.Resolve(position));
        }
Exemplo n.º 14
0
        public ActionResult Index(int k = 0)
        {
            int?[,] numbers = new int?[9, 9];

            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    string key = string.Format("f{0}{1}", i, j);
                    int number;
                    if (int.TryParse(Request[key], out number))
                        numbers[i, j] = number;
                }
            }

            Game game = new Game(numbers);
            Solver solver = new Solver();

            try
            {
                DateTime start = DateTime.Now;
                solver.Solve(game);
                DateTime end = DateTime.Now;

                ViewBag.Interval = string.Format("Solved in {0} ms.", end.Subtract(start).Milliseconds);
            }
            catch (InvalidGameException)
            {
                ViewBag.Message = "Invalid entry.  There is no solution for the game!";
            }

            ViewBag.Numbers = game.Numbers;
            return View();
        }
Exemplo n.º 15
0
  /*
   * Decompositon of cumulative.
   *
   * Inspired by the MiniZinc implementation:
   * http://www.g12.csse.unimelb.edu.au/wiki/doku.php?id=g12:zinc:lib:minizinc:std:cumulative.mzn&s[]=cumulative
   * The MiniZinc decomposition is discussed in the paper:
   * A. Schutt, T. Feydy, P.J. Stuckey, and M. G. Wallace.
   * "Why cumulative decomposition is not as bad as it sounds."
   * Download:
   * http://www.cs.mu.oz.au/%7Epjs/rcpsp/papers/cp09-cu.pdf
   * http://www.cs.mu.oz.au/%7Epjs/rcpsp/cumu_lazyfd.pdf
   *
   *
   * Parameters:
   *
   * s: start_times    assumption: IntVar[]
   * d: durations      assumption: int[]
   * r: resources      assumption: int[]
   * b: resource limit assumption: IntVar or int
   *
   *
   */
  static void MyCumulative(Solver solver,
                           IntVar[] s,
                           int[] d,
                           int[] r,
                           IntVar b) {

    int[] tasks = (from i in Enumerable.Range(0, s.Length)
                   where r[i] > 0 && d[i] > 0
                   select i).ToArray();
    int times_min = tasks.Min(i => (int)s[i].Min());
    int d_max = d.Max();
    int times_max = tasks.Max(i => (int)s[i].Max() + d_max);
    for(int t = times_min; t <= times_max; t++) {
      ArrayList bb = new ArrayList();
      foreach(int i in tasks) {
        bb.Add(((s[i] <= t) * (s[i] + d[i]> t) * r[i]).Var());
      }
      solver.Add((bb.ToArray(typeof(IntVar)) as IntVar[]).Sum() <= b);
    }

    // Somewhat experimental:
    // This constraint is needed to constrain the upper limit of b.
    if (b is IntVar) {
      solver.Add(b <= r.Sum());
    }

   }
Exemplo n.º 16
0
        public void SolverCanWinGamesButNotAll(string title, int rowStart, int colStart, GameState finalState, int rows, int cols, int[] minedCellsPositions)
        {
            var minedCells = new List<MineCell>();

            for (int i = 0; i < minedCellsPositions.Length; i += 2)
            {
                minedCells.Add(new MineCell(minedCellsPositions[i], minedCellsPositions[i + 1]));
            }

            var mineField = new MineField(rows, cols, minedCells.ToArray());
            var solver = new Solver(mineField);
            mineField.UncoverCell(rowStart, colStart);
            solver.UncoverGrid();

            Assert.Equal(mineField.GameState, finalState);

            mineField.Reset(true);

            mineField.UncoverCell(rowStart, colStart);

            for (var i = 0; i < 100 && mineField.GameState == GameState.InProgress; i++)
            {
                solver.PlayNextStep();
            }

            Assert.Equal(finalState, mineField.GameState);
        }
Exemplo n.º 17
0
        public void SolveCaseLarge()
        {
            Solver solver = new Solver();

            solver.Solve(1091.73252, 0.2, 15.44421, 656.09352);
            solver.Solve(1.03291, 0.2, 99.49224, 99999.91210);
        }
Exemplo n.º 18
0
        public void SanityCheck_GivenInsaneDataDueToWrongNumberOfBlackAndWhiteSquares_ReturnsFalse()
        {
            // Arrange
            var board = new Board(TestBoardSize);
            var solver = new Solver();
            var bogusPieceD = new Piece(
                new[]
                    {
                        //  B
                        //  W
                        // WW
                        new Square(0, 0, Colour.White),
                        new Square(1, 0, Colour.White),
                        new Square(1, 1, Colour.White),
                        new Square(1, 2, Colour.Black)
                    },
                'D');
            var pieceFeeder = new PieceFeeder(Piece.TestPieceA, Piece.TestPieceB, Piece.TestPieceC, bogusPieceD);

            // Act
            var actual = solver.SanityCheck(board, pieceFeeder);

            // Assert
            Assert.That(actual, Is.False);
        }
Exemplo n.º 19
0
  /**
   *
   * Solve the Least diff problem
   * For more info, see http://www.hakank.org/google_or_tools/least_diff.py
   *
   */
  private static void Solve()
  {
    Solver solver = new Solver("LeastDiff");

    //
    // Decision variables
    //
    IntVar A = solver.MakeIntVar(0, 9, "A");
    IntVar B = solver.MakeIntVar(0, 9, "B");
    IntVar C = solver.MakeIntVar(0, 9, "C");
    IntVar D = solver.MakeIntVar(0, 9, "D");
    IntVar E = solver.MakeIntVar(0, 9, "E");
    IntVar F = solver.MakeIntVar(0, 9, "F");
    IntVar G = solver.MakeIntVar(0, 9, "G");
    IntVar H = solver.MakeIntVar(0, 9, "H");
    IntVar I = solver.MakeIntVar(0, 9, "I");
    IntVar J = solver.MakeIntVar(0, 9, "J");

    IntVar[] all = new IntVar[] {A,B,C,D,E,F,G,H,I,J};
    int[] coeffs = {10000,1000,100,10,1};
    IntVar x = new IntVar[]{A,B,C,D,E}.ScalProd(coeffs).Var();
    IntVar y = new IntVar[]{F,G,H,I,J}.ScalProd(coeffs).Var();
    IntVar diff = (x - y).VarWithName("diff");


    //
    // Constraints
    //
    solver.Add(all.AllDifferent());
    solver.Add(A > 0);
    solver.Add(F > 0);
    solver.Add(diff > 0);


    //
    // Objective
    //
    OptimizeVar obj = diff.Minimize(1);

    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(all,
                                          Solver.CHOOSE_PATH,
                                          Solver.ASSIGN_MIN_VALUE);

    solver.NewSearch(db, obj);
    while (solver.NextSolution()) {
      Console.WriteLine("{0} - {1} = {2}  ({3}",x.Value(), y.Value(), diff.Value(), diff.ToString());
    }

    Console.WriteLine("\nSolutions: {0}", solver.Solutions());
    Console.WriteLine("WallTime: {0}ms", solver.WallTime());
    Console.WriteLine("Failures: {0}", solver.Failures());
    Console.WriteLine("Branches: {0} ", solver.Branches());

    solver.EndSearch();

  }
Exemplo n.º 20
0
 public IntGenerate( Solver solver, IntVar[] list, IntVarSelector.Select select, IntSearch search )
     : base(solver)
 {
     m_IntVarList		= list;
     m_SelectVar			= select;
     m_Search			= search;
     m_Depth				= new RevValue<double>( solver.StateStack, 1 );
 }
Exemplo n.º 21
0
 public IntGenerate( Solver solver, IntVar[] list )
     : base(solver)
 {
     m_IntVarList		= list;
     m_SelectVar			= IntVarSelector.CardinalityMin;
     m_Search			= new IntSearchDichotomize();
     m_Depth				= new RevValue<double>( solver.StateStack, 1 );
 }
Exemplo n.º 22
0
    //  We don't need helper functions here
    //  Csharp syntax is easier than C++ syntax!

    private static void CPisFun (int kBase)
    {
        //  Constraint Programming engine
        Solver solver = new Solver ("CP is fun!");

        // Decision variables
        IntVar c = solver.MakeIntVar (1, kBase - 1, "C");
        IntVar p = solver.MakeIntVar (0, kBase - 1, "P");
        IntVar i = solver.MakeIntVar (1, kBase - 1, "I");
        IntVar s = solver.MakeIntVar (0, kBase - 1, "S");
        IntVar f = solver.MakeIntVar (1, kBase - 1, "F");
        IntVar u = solver.MakeIntVar (0, kBase - 1, "U");
        IntVar n = solver.MakeIntVar (0, kBase - 1, "N");
        IntVar t = solver.MakeIntVar (1, kBase - 1, "T");
        IntVar r = solver.MakeIntVar (0, kBase - 1, "R");
        IntVar e = solver.MakeIntVar (0, kBase - 1, "E");

        // We need to group variables in a vector to be able to use
        // the global constraint AllDifferent
        IntVar[] letters = new IntVar[] { c, p, i, s, f, u, n, t, r, e};

        // Check if we have enough digits
        if (kBase < letters.Length) {
          throw new Exception("kBase < letters.Length");
        }

        //  Constraints
        solver.Add (letters.AllDifferent ());

        // CP + IS + FUN = TRUE
        solver.Add (p + s + n + kBase * (c + i + u) + kBase * kBase * f ==
               e + kBase * u + kBase * kBase * r + kBase * kBase * kBase * t);

        SolutionCollector all_solutions = solver.MakeAllSolutionCollector();
        //  Add the interesting variables to the SolutionCollector
        all_solutions.Add(c);
        all_solutions.Add(p);
        //  Create the variable kBase * c + p
        IntVar v1 = solver.MakeSum(solver.MakeProd(c, kBase), p).Var();
        //  Add it to the SolutionCollector
        all_solutions.Add(v1);

        //  Decision Builder: hot to scour the search tree
        DecisionBuilder db = solver.MakePhase (letters,
                                               Solver.CHOOSE_FIRST_UNBOUND,
                                               Solver.ASSIGN_MIN_VALUE);
        solver.Solve(db, all_solutions);

        //  Retrieve the solutions
        int numberSolutions = all_solutions.SolutionCount();
        Console.WriteLine ("Number of solutions: " + numberSolutions);

        for (int index = 0; index < numberSolutions; ++index) {
            Assignment solution = all_solutions.Solution(index);
            Console.WriteLine ("Solution found:");
            Console.WriteLine ("v1=" + solution.Value(v1));
        }
    }
Exemplo n.º 23
0
  //
  // Decomposition of alldifferent_except_0
  //
  public static void AllDifferentExcept0(Solver solver, IntVar[] a) {

    int n = a.Length;
    for(int i = 0; i < n; i++) {
      for(int j = 0; j < i; j++) {
        solver.Add((a[i] != 0) * (a[j] != 0) <= (a[i] != a[j]));
      }
    }
  }
Exemplo n.º 24
0
  public static IntVar[] subset_sum(Solver solver, 
                                    int[] values, 
                                    int total) {
    int n = values.Length;
    IntVar[] x = solver.MakeIntVarArray(n, 0, n, "x");
    solver.Add(x.ScalProd(values) == total);

    return x;
  }
Exemplo n.º 25
0
        public FltVarMatrix( Solver solver, int rowCount, int colCount, FltDomain domain )
            : base(solver)
        {
            m_VarList		= null;
            m_RowCount		= rowCount;
            m_ColCount		= colCount;

            InitMatrix( domain );
        }
Exemplo n.º 26
0
  /**
   *
   * Implements the all interval problem.
   * See http://www.hakank.org/google_or_tools/all_interval.py
   *
   */
  private static void Solve(int n=12)
  {
    Solver solver = new Solver("AllInterval");


    //
    // Decision variables
    //
    IntVar[] x =  solver.MakeIntVarArray(n, 0, n-1, "x");
    IntVar[] diffs = solver.MakeIntVarArray(n-1, 1, n-1, "diffs");

    //
    // Constraints
    //
    solver.Add(x.AllDifferent());
    solver.Add(diffs.AllDifferent());

    for(int k = 0; k < n - 1; k++) {
      // solver.Add(diffs[k] == (x[k + 1] - x[k]).Abs());
      solver.Add(diffs[k] == (x[k + 1] - x[k].Abs()));
    }


    // symmetry breaking
    solver.Add(x[0] < x[n - 1]);
    solver.Add(diffs[0] < diffs[1]);


    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(x,
                                          Solver.CHOOSE_FIRST_UNBOUND,
                                          Solver.ASSIGN_MIN_VALUE);

    solver.NewSearch(db);

    while (solver.NextSolution()) {
      Console.Write("x: ");
      for(int i = 0; i < n; i++) {
          Console.Write("{0} ", x[i].Value());
      }
      Console.Write("  diffs: ");
      for(int i = 0; i < n-1; i++) {
          Console.Write("{0} ", diffs[i].Value());
      }
      Console.WriteLine();
    }

    Console.WriteLine("\nSolutions: {0}", solver.Solutions());
    Console.WriteLine("WallTime: {0}ms", solver.WallTime());
    Console.WriteLine("Failures: {0}", solver.Failures());
    Console.WriteLine("Branches: {0} ", solver.Branches());

    solver.EndSearch();

  }
Exemplo n.º 27
0
  /**
   * Ensure that the sum of the segments
   * in cc == res
   *
   */
  public static void calc(Solver solver,
                           int[] cc,
                           IntVar[,] x,
                           int res)
  {

    int ccLen = cc.Length;
    if (ccLen == 4) {

      // for two operands there's
      // a lot of possible variants
      IntVar a = x[cc[0]-1, cc[1]-1];
      IntVar b = x[cc[2]-1, cc[3]-1];

      IntVar r1 = a + b == res;
      IntVar r2 = a * b == res;
      IntVar r3 = a * res == b;
      IntVar r4 = b * res == a;
      IntVar r5 = a - b == res;
      IntVar r6 = b - a == res;

      solver.Add(r1+r2+r3+r4+r5+r6 >= 1);

    } else {

      // For length > 2 then res is either the sum
      // the the product of the segment

      // sum the numbers
      int len = cc.Length / 2;
      IntVar[] xx = (from i in Enumerable.Range(0, len)
                     select x[cc[i*2]-1,cc[i*2+1]-1]).ToArray();

      // Sum
      IntVar this_sum = xx.Sum() == res;

      // Product
      // IntVar this_prod = (xx.Prod() == res).Var(); // don't work
      IntVar this_prod;
      if (xx.Length == 3) {
        this_prod = (x[cc[0]-1,cc[1]-1] *
                     x[cc[2]-1,cc[3]-1] *
                     x[cc[4]-1,cc[5]-1]) == res;
      } else {
        this_prod = (
                     x[cc[0]-1,cc[1]-1] *
                     x[cc[2]-1,cc[3]-1] *
                     x[cc[4]-1,cc[5]-1] *
                     x[cc[6]-1,cc[7]-1]) == res;

      }

      solver.Add(this_sum + this_prod >= 1);


    }
  }
Exemplo n.º 28
0
  /**
   *
   * Scheduling speakers problem
   *
   *  From Rina Dechter, Constraint Processing, page 72
   *  Scheduling of 6 speakers in 6 slots.
   *
   * See http://www.hakank.org/google_or_tools/scheduling_speakers.py
   *
   */
  private static void Solve()
  {
    Solver solver = new Solver("SchedulingSpeakers");


    // number of speakers
    int n = 6;

    // slots available to speak
    int[][] available = {
                    // Reasoning:
      new int[] {3,4,5,6},    // 2) the only one with 6 after speaker F -> 1
      new int[] {3,4},        // 5) 3 or 4
      new int[] {2,3,4,5},    // 3) only with 5 after F -> 1 and A -> 6
      new int[] {2,3,4},      // 4) only with 2 after C -> 5 and F -> 1
      new int[] {3,4},        // 5) 3 or 4
      new int[] {1,2,3,4,5,6} // 1) the only with 1
    };


    //
    // Decision variables
    //
    IntVar[] x =  solver.MakeIntVarArray(n, 1, n, "x");

    //
    // Constraints
    //
    solver.Add(x.AllDifferent());

    for(int i = 0; i < n; i++) {
      solver.Add(x[i].Member(available[i]));
    }


    //
    // Search
    //
    DecisionBuilder db = solver.MakePhase(x,
                                          Solver.CHOOSE_FIRST_UNBOUND,
                                          Solver.ASSIGN_MIN_VALUE);

    solver.NewSearch(db);

    while (solver.NextSolution()) {
      Console.WriteLine(string.Join(",", (from i in x select i.Value())));
    }

    Console.WriteLine("\nSolutions: {0}", solver.Solutions());
    Console.WriteLine("WallTime: {0}ms", solver.WallTime());
    Console.WriteLine("Failures: {0}", solver.Failures());
    Console.WriteLine("Branches: {0} ", solver.Branches());

    solver.EndSearch();

  }
Exemplo n.º 29
0
  /*
   * Global constraint regular
   *
   * This is a translation of MiniZinc's regular constraint (defined in
   * lib/zinc/globals.mzn), via the Comet code refered above.
   * All comments are from the MiniZinc code.
   * """
   * The sequence of values in array 'x' (which must all be in the range 1..S)
   * is accepted by the DFA of 'Q' states with input 1..S and transition
   * function 'd' (which maps (1..Q, 1..S) -> 0..Q)) and initial state 'q0'
   * (which must be in 1..Q) and accepting states 'F' (which all must be in
   * 1..Q).  We reserve state 0 to be an always failing state.
   * """
   *
   * x : IntVar array
   * Q : number of states
   * S : input_max
   * d : transition matrix
   * q0: initial state
   * F : accepting states
   *
   */
  static void MyRegular(Solver solver,
                        IntVar[] x,
                        int Q,
                        int S,
                        int[,] d,
                        int q0,
                        int[] F) {



    Debug.Assert(Q > 0, "regular: 'Q' must be greater than zero");
    Debug.Assert(S > 0, "regular: 'S' must be greater than zero");

    // d2 is the same as d, except we add one extra transition for
    // each possible input;  each extra transition is from state zero
    // to state zero.  This allows us to continue even if we hit a
    // non-accepted input.
    int[][] d2 = new int[Q+1][];
    for(int i = 0; i <= Q; i++) {
      int[] row = new int[S];
      for(int j = 0; j < S; j++) {
        if (i == 0) {
          row[j] = 0;
        } else {
          row[j] = d[i-1,j];
        }
      }
      d2[i] = row;
    }

    int[] d2_flatten = (from i in Enumerable.Range(0, Q+1)
                        from j in Enumerable.Range(0, S)
                        select d2[i][j]).ToArray();

    // If x has index set m..n, then a[m-1] holds the initial state
    // (q0), and a[i+1] holds the state we're in after processing
    // x[i].  If a[n] is in F, then we succeed (ie. accept the
    // string).
    int m = 0;
    int n = x.Length;

    IntVar[] a = solver.MakeIntVarArray(n+1-m, 0,Q+1, "a");
    // Check that the final state is in F
    solver.Add(a[a.Length-1].Member(F));
    // First state is q0
    solver.Add(a[m] == q0);

    for(int i = 0; i < n; i++) {
      solver.Add(x[i] >= 1);
      solver.Add(x[i] <= S);
      // Determine a[i+1]: a[i+1] == d2[a[i], x[i]]
      solver.Add(a[i+1] == d2_flatten.Element(((a[i]*S)+(x[i]-1))));

    }

  }
 public static void Main(string[] args)
 {
     Stream inputStream = Console.OpenStandardInput();
     InputReader inp = new InputReader(inputStream);
     Stream outputStream = Console.OpenStandardOutput();
     OutputWriter outp = new OutputWriter(outputStream);
     Solver algorithm = new Solver();
     algorithm.solve(inp, outp);
     outp.close();
 }
Exemplo n.º 31
0
    /**
     *
     * Solves a set covering deployment problem.
     * See  See http://www.hakank.org/or-tools/set_covering_deployment.py
     *
     */
    private static void Solve()
    {
        Solver solver = new Solver("SetCoveringDeployment");

        //
        // data
        //

        // From http://mathworld.wolfram.com/SetCoveringDeployment.html
        string[] countries = { "Alexandria",
                               "Asia Minor",
                               "Britain",
                               "Byzantium",
                               "Gaul",
                               "Iberia",
                               "Rome",
                               "Tunis" };

        int n = countries.Length;

        // the incidence matrix (neighbours)
        int[,] mat = { { 0, 1, 0, 1, 0, 0, 1, 1 },
                       { 1, 0, 0, 1, 0, 0, 0, 0 },
                       { 0, 0, 0, 0, 1, 1, 0, 0 },
                       { 1, 1, 0, 0, 0, 0, 1, 0 },
                       { 0, 0, 1, 0, 0, 1, 1, 0 },
                       { 0, 0, 1, 0, 1, 0, 1, 1 },
                       { 1, 0, 0, 1, 1, 1, 0, 1 },
                       { 1, 0, 0, 0, 0, 1, 1, 0 } };

        //
        // Decision variables
        //

        // First army
        IntVar[] x = solver.MakeIntVarArray(n, 0, 1, "x");

        // Second (reserve) army
        IntVar[] y = solver.MakeIntVarArray(n, 0, 1, "y");

        // total number of armies
        IntVar num_armies = (x.Sum() + y.Sum()).Var();


        //
        // Constraints
        //

        //
        //  Constraint 1: There is always an army in a city
        //                (+ maybe a backup)
        //                Or rather: Is there a backup, there
        //                must be an an army
        //
        for (int i = 0; i < n; i++)
        {
            solver.Add(x[i] >= y[i]);
        }

        //
        // Constraint 2: There should always be an backup
        //               army near every city
        //
        for (int i = 0; i < n; i++)
        {
            IntVar[] count_neighbours = (
                from j in Enumerable.Range(0, n)
                where mat[i, j] == 1
                select(y[j])).ToArray();

            solver.Add((x[i] + count_neighbours.Sum()) >= 1);
        }


        //
        // objective
        //
        OptimizeVar objective = num_armies.Minimize(1);


        //
        // Search
        //
        DecisionBuilder db = solver.MakePhase(x,
                                              Solver.INT_VAR_DEFAULT,
                                              Solver.INT_VALUE_DEFAULT);

        solver.NewSearch(db, objective);

        while (solver.NextSolution())
        {
            Console.WriteLine("num_armies: " + num_armies.Value());
            for (int i = 0; i < n; i++)
            {
                if (x[i].Value() == 1)
                {
                    Console.Write("Army: " + countries[i] + " ");
                }

                if (y[i].Value() == 1)
                {
                    Console.WriteLine(" Reverse army: " + countries[i]);
                }
            }
            Console.WriteLine("\n");
        }

        Console.WriteLine("\nSolutions: {0}", solver.Solutions());
        Console.WriteLine("WallTime: {0}ms", solver.WallTime());
        Console.WriteLine("Failures: {0}", solver.Failures());
        Console.WriteLine("Branches: {0} ", solver.Branches());

        solver.EndSearch();
    }
Exemplo n.º 32
0
 public void InitializeDamage(Solver solver, bool areaEffect, int range, MagicSchool magicSchool, SpellData spellData, float hitProcs, float castProcs, float dotDuration)
 {
     InitializeDamage(solver, areaEffect, range, magicSchool, spellData.Cost, spellData.MinDamage, spellData.MaxDamage, spellData.SpellDamageCoefficient, spellData.PeriodicDamage, spellData.DotDamageCoefficient, hitProcs, castProcs, dotDuration);
 }
Exemplo n.º 33
0
        public void InitializeEffectDamage(Solver solver, MagicSchool magicSchool, float minDamage, float maxDamage)
        {
            Stats                  baseStats          = solver.BaseStats;
            MageTalents            mageTalents        = solver.MageTalents;
            CalculationOptionsMage calculationOptions = solver.CalculationOptions;

            //AreaEffect = areaEffect;
            //BaseCost = cost - (int)baseStats.SpellsManaReduction;
            MagicSchool   = magicSchool;
            BaseMinDamage = minDamage;
            BaseMaxDamage = maxDamage;
            //BasePeriodicDamage = periodicDamage;
            //SpellDamageCoefficient = spellDamageCoefficient;
            //Ticks = 1;
            //CastProcs = 0;
            //CastProcs2 = 0;
            //DotDamageCoefficient = dotDamageCoefficient;
            //DotDuration = dotDuration;

            BaseDirectDamageModifier = 1.0f;
            BaseDotDamageModifier    = 1.0f;
            BaseCostModifier         = 1.0f;

            //Range = range;

            /*float baseCostAmplifier = calculationOptions.EffectCostMultiplier;
             * baseCostAmplifier *= (1.0f - 0.01f * mageTalents.Precision);
             * if (mageTalents.FrostChanneling > 0) baseCostAmplifier *= (1.0f - 0.01f - 0.03f * mageTalents.FrostChanneling);
             * if (MagicSchool == MagicSchool.Arcane) baseCostAmplifier *= (1.0f - 0.01f * mageTalents.ArcaneFocus);
             * BaseCostAmplifier = baseCostAmplifier;*/

            /*float baseInterruptProtection = baseStats.InterruptProtection;
             * if (MagicSchool == MagicSchool.Fire || MagicSchool == MagicSchool.FrostFire)
             * {
             *  baseInterruptProtection += 0.35f * mageTalents.BurningSoul;
             *  AffectedByFlameCap = true;
             * }
             * BaseInterruptProtection = baseInterruptProtection;*/

            float realResistance;

            switch (MagicSchool)
            {
            case MagicSchool.Arcane:
                BaseSpellModifier         = solver.BaseArcaneSpellModifier;
                BaseAdditiveSpellModifier = solver.BaseArcaneAdditiveSpellModifier;
                BaseCritRate     = solver.BaseArcaneCritRate;
                CritBonus        = solver.BaseArcaneCritBonus;
                HitRate          = solver.BaseArcaneHitRate;
                ThreatMultiplier = solver.ArcaneThreatMultiplier;
                realResistance   = calculationOptions.ArcaneResist;
                break;

            case MagicSchool.Fire:
                BaseSpellModifier         = solver.BaseFireSpellModifier;
                BaseAdditiveSpellModifier = solver.BaseFireAdditiveSpellModifier;
                BaseCritRate          = solver.BaseFireCritRate;
                CritBonus             = solver.BaseFireCritBonus;
                HitRate               = solver.BaseFireHitRate;
                ThreatMultiplier      = solver.FireThreatMultiplier;
                realResistance        = calculationOptions.FireResist;
                BaseDotDamageModifier = 1.0f + solver.FlashburnBonus;
                break;

            case MagicSchool.FrostFire:
                BaseSpellModifier         = solver.BaseFrostFireSpellModifier;
                BaseAdditiveSpellModifier = solver.BaseFrostFireAdditiveSpellModifier;
                BaseCritRate     = solver.BaseFrostFireCritRate;
                CritBonus        = solver.BaseFrostFireCritBonus;
                HitRate          = solver.BaseFrostFireHitRate;
                ThreatMultiplier = solver.FrostFireThreatMultiplier;
                if (calculationOptions.FireResist == -1)
                {
                    realResistance = calculationOptions.FrostResist;
                }
                else if (calculationOptions.FrostResist == -1)
                {
                    realResistance = calculationOptions.FireResist;
                }
                else
                {
                    realResistance = Math.Min(calculationOptions.FireResist, calculationOptions.FrostResist);
                }
                BaseDotDamageModifier = 1.0f + solver.FlashburnBonus;
                break;

            case MagicSchool.Frost:
                BaseSpellModifier         = solver.BaseFrostSpellModifier;
                BaseAdditiveSpellModifier = solver.BaseFrostAdditiveSpellModifier;
                BaseCritRate     = solver.BaseFrostCritRate;
                CritBonus        = solver.BaseFrostCritBonus;
                HitRate          = solver.BaseFrostHitRate;
                ThreatMultiplier = solver.FrostThreatMultiplier;
                realResistance   = calculationOptions.FrostResist;
                break;

            case MagicSchool.Nature:
                BaseSpellModifier         = solver.BaseNatureSpellModifier;
                BaseAdditiveSpellModifier = solver.BaseNatureAdditiveSpellModifier;
                BaseCritRate     = solver.BaseNatureCritRate;
                CritBonus        = solver.BaseNatureCritBonus;
                HitRate          = solver.BaseNatureHitRate;
                ThreatMultiplier = solver.NatureThreatMultiplier;
                realResistance   = calculationOptions.NatureResist;
                break;

            case MagicSchool.Shadow:
                BaseSpellModifier         = solver.BaseShadowSpellModifier;
                BaseAdditiveSpellModifier = solver.BaseShadowAdditiveSpellModifier;
                BaseCritRate     = solver.BaseShadowCritRate;
                CritBonus        = solver.BaseShadowCritBonus;
                HitRate          = solver.BaseShadowHitRate;
                ThreatMultiplier = solver.ShadowThreatMultiplier;
                realResistance   = calculationOptions.ShadowResist;
                break;

            case MagicSchool.Holy:
            default:
                BaseSpellModifier         = solver.BaseHolySpellModifier;
                BaseAdditiveSpellModifier = solver.BaseHolyAdditiveSpellModifier;
                BaseCritRate     = solver.BaseHolyCritRate;
                CritBonus        = solver.BaseHolyCritBonus;
                HitRate          = solver.BaseHolyHitRate;
                ThreatMultiplier = solver.HolyThreatMultiplier;
                realResistance   = calculationOptions.HolyResist;
                break;
            }

            NonHSCritRate = baseStats.SpellCritOnTarget;
            IgniteFactor  = 0;

            int playerLevel = calculationOptions.PlayerLevel;
            int targetLevel = calculationOptions.TargetLevel;

            /*if (areaEffect)
             * {
             *  targetLevel = calculationOptions.AoeTargetLevel;
             *  float hitRate = ((targetLevel <= playerLevel + 2) ? (0.96f - (targetLevel - playerLevel) * 0.01f) : (0.94f - (targetLevel - playerLevel - 2) * 0.11f)) + calculations.BaseSpellHit;
             *  if (MagicSchool == MagicSchool.Arcane) hitRate += 0.01f * mageTalents.ArcaneFocus;
             *  if (hitRate > Spell.MaxHitRate) hitRate = Spell.MaxHitRate;
             *  HitRate = hitRate;
             * }
             * else
             * {
             *  targetLevel = calculationOptions.TargetLevel;
             * }*/

            RealResistance      = realResistance;
            PartialResistFactor = (realResistance == -1) ? 0 : (1 - StatConversion.GetAverageResistance(playerLevel, targetLevel, realResistance, baseStats.SpellPenetration));
        }
Exemplo n.º 34
0
    /**
     *
     * Sicherman Dice.
     *
     * From http://en.wikipedia.org/wiki/Sicherman_dice
     * ""
     * Sicherman dice are the only pair of 6-sided dice which are not normal dice,
     * bear only positive integers, and have the same probability distribution for
     * the sum as normal dice.
     *
     * The faces on the dice are numbered 1, 2, 2, 3, 3, 4 and 1, 3, 4, 5, 6, 8.
     * ""
     *
     * I read about this problem in a book/column by Martin Gardner long
     * time ago, and got inspired to model it now by the WolframBlog post
     * "Sicherman Dice": http://blog.wolfram.com/2010/07/13/sicherman-dice/
     *
     * This model gets the two different ways, first the standard way and
     * then the Sicherman dice:
     *
     *  x1 = [1, 2, 3, 4, 5, 6]
     *  x2 = [1, 2, 3, 4, 5, 6]
     *  ----------
     *  x1 = [1, 2, 2, 3, 3, 4]
     *  x2 = [1, 3, 4, 5, 6, 8]
     *
     *
     * Extra: If we also allow 0 (zero) as a valid value then the
     * following two solutions are also valid:
     *
     * x1 = [0, 1, 1, 2, 2, 3]
     * x2 = [2, 4, 5, 6, 7, 9]
     * ----------
     * x1 = [0, 1, 2, 3, 4, 5]
     * x2 = [2, 3, 4, 5, 6, 7]
     *
     * These two extra cases are mentioned here:
     * http://mathworld.wolfram.com/SichermanDice.html
     *
     *
     * Also see http://www.hakank.org/or-tools/sicherman_dice.py
     *
     */
    private static void Solve()
    {
        Solver solver = new Solver("SichermanDice");

        //
        // Data
        //
        int n            = 6;
        int m            = 10;
        int lowest_value = 0;

        // standard distribution
        int[] standard_dist = { 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1 };


        IEnumerable <int> RANGE  = Enumerable.Range(0, n);
        IEnumerable <int> RANGE1 = Enumerable.Range(0, n - 1);


        //
        // Decision variables
        //

        IntVar[] x1 = solver.MakeIntVarArray(n, lowest_value, m, "x1");
        IntVar[] x2 = solver.MakeIntVarArray(n, lowest_value, m, "x2");

        //
        // Constraints
        //
        for (int k = 0; k < standard_dist.Length; k++)
        {
            solver.Add((from i in RANGE
                        from j in RANGE
                        select x1[i] + x2[j] == k + 2
                        ).ToArray().Sum() == standard_dist[k]);
        }

        // symmetry breaking
        foreach (int i in RANGE1)
        {
            solver.Add(x1[i] <= x1[i + 1]);
            solver.Add(x2[i] <= x2[i + 1]);
            solver.Add(x1[i] <= x2[i]);
        }


        //
        // Search
        //
        DecisionBuilder db = solver.MakePhase(x1.Concat(x2).ToArray(),
                                              Solver.INT_VAR_DEFAULT,
                                              Solver.INT_VALUE_DEFAULT);

        solver.NewSearch(db);

        while (solver.NextSolution())
        {
            Console.Write("x1: ");
            foreach (int i in RANGE)
            {
                Console.Write(x1[i].Value() + " ");
            }
            Console.Write("\nx2: ");
            foreach (int i in RANGE)
            {
                Console.Write(x2[i].Value() + " ");
            }
            Console.WriteLine("\n");
        }

        Console.WriteLine("\nSolutions: {0}", solver.Solutions());
        Console.WriteLine("WallTime: {0}ms", solver.WallTime());
        Console.WriteLine("Failures: {0}", solver.Failures());
        Console.WriteLine("Branches: {0} ", solver.Branches());

        solver.EndSearch();
    }
Exemplo n.º 35
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            Solver.CeroDivision();

            TextBox1.Text = "Se guardo una nueva excepcion en: " + WebConfigurationManager.AppSettings["Exeptions"];
        }
Exemplo n.º 36
0
 protected IntVarExpr(Solver solver, Variable[] varList) :
     base(solver, varList)
 {
 }
Exemplo n.º 37
0
 public object SolvePart1()
 {
     return(Solver.TreesCount(_cells, 3, 1));
 }
        public Individual <List <Genome>, Problem, Fitness> CrossOver(
            Solver <List <Genome>, Problem, Fitness> solver, Individual <List <Genome>, Problem, Fitness> parent1, Individual <List <Genome>, Problem, Fitness> parent2)
        {
            throw new NotImplementedException("Not re-implemented after refactoring GA");
            //List<Genome> genomes = null;

            //Individual new_individual = new Individual();

            //List<Genome> parent1_genomes = parent1.Copy().Genomes;
            //List<Genome> parent2_genomes = parent2.Copy().Genomes;

            //// select the 'best' genomes.

            //genomes = new List<Genome>();
            //while (parent1_genomes.Count > 0 || parent2_genomes.Count > 0)
            //{
            //    // try from parent 1
            //    Genome genome = null;
            //    if (parent1_genomes.Count > 0)
            //    {
            //        genome = parent1_genomes[StaticRandomGenerator.Get().Generate(parent1_genomes.Count)];
            //        if (!IndividualHelper.Overlaps(genomes, genome))
            //        {
            //            genomes.Add(genome);
            //        }
            //        parent1_genomes.Remove(genome);
            //    }
            //    if (parent2_genomes.Count > 0)
            //    {
            //        genome = parent2_genomes[StaticRandomGenerator.Get().Generate(parent2_genomes.Count)];
            //        if (!IndividualHelper.Overlaps(genomes, genome))
            //        {
            //            genomes.Add(genome);
            //        }
            //        parent2_genomes.Remove(genome);
            //    }
            //}

            //// list the rest of the cities and divide them into new routes.
            //List<int> rest = new List<int>();
            //for (int city_to_place = 0; city_to_place < solver.Problem.Cities; city_to_place++)
            //{
            //    if (!IndividualHelper.Overlaps(genomes, city_to_place))
            //    {
            //        rest.Add(city_to_place);
            //    }
            //}

            //// create the new individual.
            //new_individual.Initialize(genomes);
            //new_individual.CalculateFitness(
            //    solver.Problem,
            //    solver.FitnessCalculator,
            //    false);

            //// TODO: place the rest of the cities in existing rounds.
            //List<int> failed = new List<int>();
            //while (rest.Count > 0)
            //{
            //    // select random from current.
            //    int current_city = rest[StaticRandomGenerator.Get().Generate(
            //        rest.Count)];
            //    rest.Remove(current_city);

            //    // make a list of potential targets.
            //    List<Genome> potential_genomes = new List<Genome>();
            //    for (int round_idx = 0; round_idx < genomes.Count; round_idx++)
            //    {
            //        if (new_individual.Fitness.LargestRoundCategories[round_idx] == 0)
            //        {
            //            potential_genomes.Add(new_individual.Genomes[round_idx]);
            //        }
            //    }

            //    // try to place the current city in one of the targets.
            //    bool succes = false;
            //    while (potential_genomes.Count > 0)
            //    {
            //        int random_idx = StaticRandomGenerator.Get().Generate(potential_genomes.Count);
            //        Genome current = potential_genomes[random_idx];
            //        int genome_idx = new_individual.Genomes.IndexOf(current);
            //        current = new Genome(current);
            //        potential_genomes.RemoveAt(random_idx);

            //        Individual<List<Genome>, Problem, Fitness> copy = new_individual.Copy();

            //        OsmSharp.Math.VRP.MultiSalesman.Genetic.Helpers.BestPlacementHelper.BestPlacementResult result =
            //            BestPlacementHelper.CalculateBestPlacementInGenome(
            //                solver.Problem,
            //                solver.FitnessCalculator as FitnessCalculator,
            //                current,
            //                current_city);

            //        // do the placement.
            //        IndividualHelper.PlaceInGenome(
            //            current,
            //            result.CityIdx,
            //            result.City);

            //        // re-calculate fitness
            //        copy.Genomes[genome_idx] = current;
            //        copy.CalculateFitness(solver.Problem, solver.FitnessCalculator, false);

            //        // if the round is still not too big; keep the result.
            //        if (copy.Fitness.LargestRoundCategories[genome_idx] == 0)
            //        {
            //            new_individual = (copy as Individual);
            //            succes = true;
            //            break;
            //        }
            //    }

            //    // add to failed if not succesfull
            //    if (!succes)
            //    {
            //        failed.Add(current_city);
            //    }
            //}
            //rest = failed;

            //bool new_round = true;
            //Genome current_round = null;
            //double previous_time = 0;
            //while (rest.Count > 0)
            //{
            //    // create a new round if needed.
            //    int city;
            //    int city_idx;

            //    // force placement if less than half of the average round size remains.
            //    int size = solver.Problem.Cities / new_individual.Genomes.Count;
            //    if (new_round && rest.Count < size / 2)
            //    {
            //        new_individual = BestPlacementHelper.DoFast(
            //            solver.Problem,
            //            solver.FitnessCalculator as FitnessCalculator,
            //            new_individual,
            //            rest);

            //        rest.Clear();

            //        break;
            //    }

            //    if (new_round)
            //    {
            //        new_round = false;
            //        current_round = new Genome();
            //        new_individual.Genomes.Add(current_round);

            //        // select a random city to place.
            //        city_idx = StaticRandomGenerator.Get().Generate(rest.Count);
            //        city = rest[city_idx];
            //        rest.RemoveAt(city_idx);
            //        current_round.Add(city);

            //        previous_time = solver.Problem.TargetTime.Value;
            //    }

            //    if (rest.Count > 0)
            //    {
            //        // find the best city to place next.
            //        // calculate the best position to place the next city.
            //        BestPlacementHelper.BestPlacementResult new_position_to_place =
            //            BestPlacementHelper.CalculateBestPlacementInGenome(
            //                solver.Problem,
            //                solver.FitnessCalculator as FitnessCalculator,
            //                current_round,
            //                rest);

            //        city = new_position_to_place.City;

            //        // remove the node from the source list.
            //        rest.Remove(city);

            //        // place the node.
            //        current_round.Insert(new_position_to_place.CityIdx, new_position_to_place.City);

            //        // calculate the time.
            //        double time = (solver.FitnessCalculator as FitnessCalculator).CalculateTime(
            //            solver.Problem, current_round);

            //        if (solver.Problem.TargetTime.Value < time)
            //        { // time limit has been reached.
            //            double diff_average = time - solver.Problem.TargetTime.Value;
            //            double diff_previous = solver.Problem.TargetTime.Value - previous_time;

            //            if (diff_average > diff_previous)
            //            { // remove the last added city.
            //                current_round.Remove(city);
            //                rest.Add(city);
            //            }
            //            else
            //            { // keep the last city.

            //            }

            //            // keep the generated round.
            //            new_round = true;
            //        }
            //        previous_time = time;
            //    }
            //}

            //new_individual.CalculateFitness(
            //    solver.Problem,
            //    solver.FitnessCalculator);

            //return new_individual;
        }
Exemplo n.º 39
0
    public static void Main(String[] args)
    {
        // Instantiate the solver.
        // [START solver]
        Solver solver = new Solver("CP is fun!");
        // [END solver]

        // [START variables]
        const int kBase = 10;

        // Decision variables.
        IntVar c = solver.MakeIntVar(1, kBase - 1, "C");
        IntVar p = solver.MakeIntVar(0, kBase - 1, "P");
        IntVar i = solver.MakeIntVar(1, kBase - 1, "I");
        IntVar s = solver.MakeIntVar(0, kBase - 1, "S");
        IntVar f = solver.MakeIntVar(1, kBase - 1, "F");
        IntVar u = solver.MakeIntVar(0, kBase - 1, "U");
        IntVar n = solver.MakeIntVar(0, kBase - 1, "N");
        IntVar t = solver.MakeIntVar(1, kBase - 1, "T");
        IntVar r = solver.MakeIntVar(0, kBase - 1, "R");
        IntVar e = solver.MakeIntVar(0, kBase - 1, "E");

        // Group variables in a vector so that we can use AllDifferent.
        IntVar[] letters = new IntVar[] { c, p, i, s, f, u, n, t, r, e };

        // Verify that we have enough digits.
        if (kBase < letters.Length)
        {
            throw new Exception("kBase < letters.Length");
        }
        // [END variables]

        // Define constraints.
        // [START constraints]
        solver.Add(letters.AllDifferent());

        // CP + IS + FUN = TRUE
        solver.Add(p + s + n + kBase * (c + i + u) + kBase * kBase * f ==
                   e + kBase * u + kBase * kBase * r + kBase * kBase * kBase * t);
        // [END constraints]

        // [START solve]
        int SolutionCount = 0;
        // Create the decision builder to search for solutions.
        DecisionBuilder db = solver.MakePhase(letters, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);

        solver.NewSearch(db);
        while (solver.NextSolution())
        {
            Console.Write("C=" + c.Value() + " P=" + p.Value());
            Console.Write(" I=" + i.Value() + " S=" + s.Value());
            Console.Write(" F=" + f.Value() + " U=" + u.Value());
            Console.Write(" N=" + n.Value() + " T=" + t.Value());
            Console.Write(" R=" + r.Value() + " E=" + e.Value());
            Console.WriteLine();

            // Is CP + IS + FUN = TRUE?
            if (p.Value() + s.Value() + n.Value() + kBase * (c.Value() + i.Value() + u.Value()) +
                kBase * kBase * f.Value() !=
                e.Value() + kBase * u.Value() + kBase * kBase * r.Value() + kBase * kBase * kBase * t.Value())
            {
                throw new Exception("CP + IS + FUN != TRUE");
            }
            SolutionCount++;
        }
        solver.EndSearch();
        Console.WriteLine($"Number of solutions found: {SolutionCount}");
        // [END solve]
    }
Exemplo n.º 40
0
    /**
     *
     * Combinatorial auction.
     *
     * This is a more general model for the combinatorial example
     * in the Numberjack Tutorial, pages 9 and 24 (slides  19/175 and
     * 51/175).
     *
     * See http://www.hakank.org/or-tools/combinatorial_auction2.py
     *
     * The original and more talkative model is here:
     * http://www.hakank.org/numberjack/combinatorial_auction.py
     *
     */
    private static void Solve()
    {
        Solver solver = new Solver("CombinatorialAuction2");

        //
        // Data
        //
        int n = 5;

        // the items for each bid
        int[][] items =
        {
            new int[] { 0, 1 }, // A,B
            new int[] { 0, 2 }, // A, C
            new int[] { 1, 3 }, // B,D
            new int[] { 1,2, 3 }, // B,C,D
            new int[] { 0 }     // A
        };

        int[] bid_ids    = { 0, 1, 2, 3 };
        int[] bid_amount = { 10, 20, 30, 40, 14 };

        //
        // Decision variables
        //
        IntVar[] x = solver.MakeIntVarArray(n, 0, 1, "x");
        IntVar   z = x.ScalProd(bid_amount).VarWithName("z");

        //
        // Constraints
        //

        foreach (int bid_id in bid_ids)
        {
            var tmp2 = (from item in Enumerable.Range(0, n)
                        from i in Enumerable.Range(0, items[item].Length)
                        where items [item]
                        [i] == bid_id select x[item]);

            solver.Add(tmp2.ToArray().Sum() <= 1);
        }

        //
        // Objective
        //
        OptimizeVar obj = z.Maximize(1);

        //
        // Search
        //
        DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);

        solver.NewSearch(db, obj);

        while (solver.NextSolution())
        {
            Console.Write("z: {0,2} x: ", z.Value());
            for (int i = 0; i < n; i++)
            {
                Console.Write(x[i].Value() + " ");
            }
            Console.WriteLine();
        }

        Console.WriteLine("\nSolutions: {0}", solver.Solutions());
        Console.WriteLine("WallTime: {0}ms", solver.WallTime());
        Console.WriteLine("Failures: {0}", solver.Failures());
        Console.WriteLine("Branches: {0} ", solver.Branches());

        solver.EndSearch();
    }
Exemplo n.º 41
0
    /**
     *
     * Solves the N-Queens problem.
     *
     * Syntax: nqueens.exe n num print
     * where
     *    n    : size of board
     *    num  : number of solutions to calculate
     *    print: print the results (if > 0)
     *
     */
    private static void Solve(int n = 8, int num = 0, int print = 1)
    {
        Solver solver = new Solver("N-Queens");

        //
        // Decision variables
        //
        IntVar[] q = solver.MakeIntVarArray(n, 0, n - 1, "q");

        //
        // Constraints
        //
        solver.Add(q.AllDifferent());

        IntVar[] q1 = new IntVar[n];
        IntVar[] q2 = new IntVar[n];
        for (int i = 0; i < n; i++)
        {
            q1[i] = (q[i] + i).Var();
            q2[i] = (q[i] - i).Var();
        }
        solver.Add(q1.AllDifferent());
        solver.Add(q2.AllDifferent());

        // Alternative version: it works as well but are not that clear

        /*
         * solver.Add((from i in Enumerable.Range(0, n)
         *          select (q[i] + i).Var()).ToArray().AllDifferent());
         *
         * solver.Add((from i in Enumerable.Range(0, n)
         *          select (q[i] - i).Var()).ToArray().AllDifferent());
         */

        //
        // Search
        //
        DecisionBuilder db =
            solver.MakePhase(q, Solver.CHOOSE_MIN_SIZE_LOWEST_MAX, Solver.ASSIGN_CENTER_VALUE);

        solver.NewSearch(db);
        int c = 0;

        while (solver.NextSolution())
        {
            if (print > 0)
            {
                for (int i = 0; i < n; i++)
                {
                    Console.Write("{0} ", q[i].Value());
                }

                Console.WriteLine();
            }
            c++;
            if (num > 0 && c >= num)
            {
                break;
            }
        }

        Console.WriteLine("\nSolutions: {0}", solver.Solutions());
        Console.WriteLine("WallTime: {0}ms", solver.WallTime());
        Console.WriteLine("Failures: {0}", solver.Failures());
        Console.WriteLine("Branches: {0} ", solver.Branches());

        solver.EndSearch();
    }
Exemplo n.º 42
0
    static void Main(string[] args)
    {
        Solver s = new Solver();

        s.Solve();
    }
Exemplo n.º 43
0
        ///<summary>
        /// Removes a space object from the simulation.
        ///</summary>
        ///<param name="spaceObject">Space object to remove.</param>
        public void Remove(ISpaceObject spaceObject)
        {
            if (spaceObject.Space != this)
            {
                throw new ArgumentException("The object does not belong to this space; cannot remove it.");
            }

            SimulationIslandMember simulationIslandMember = spaceObject as SimulationIslandMember;

            if (simulationIslandMember != null)
            {
                DeactivationManager.Remove(simulationIslandMember);
            }

            ISimulationIslandMemberOwner simulationIslandMemberOwner = spaceObject as ISimulationIslandMemberOwner;

            if (simulationIslandMemberOwner != null)
            {
                DeactivationManager.Remove(simulationIslandMemberOwner.ActivityInformation);
            }

            //Go through each stage, removing the space object from it if necessary.
            IForceUpdateable velocityUpdateable = spaceObject as IForceUpdateable;

            if (velocityUpdateable != null)
            {
                ForceUpdater.Remove(velocityUpdateable);
            }

            MobileCollidable boundingBoxUpdateable = spaceObject as MobileCollidable;

            if (boundingBoxUpdateable != null)
            {
                BoundingBoxUpdater.Remove(boundingBoxUpdateable);
            }

            BroadPhaseEntry broadPhaseEntry = spaceObject as BroadPhaseEntry;

            if (broadPhaseEntry != null)
            {
                BroadPhase.Remove(broadPhaseEntry);
            }

            //Entites own collision proxies, but are not entries themselves.
            IBroadPhaseEntryOwner broadPhaseEntryOwner = spaceObject as IBroadPhaseEntryOwner;

            if (broadPhaseEntryOwner != null)
            {
                BroadPhase.Remove(broadPhaseEntryOwner.Entry);
                boundingBoxUpdateable = broadPhaseEntryOwner.Entry as MobileCollidable;
                if (boundingBoxUpdateable != null)
                {
                    BoundingBoxUpdater.Remove(boundingBoxUpdateable);
                }
            }

            SolverUpdateable solverUpdateable = spaceObject as SolverUpdateable;

            if (solverUpdateable != null)
            {
                Solver.Remove(solverUpdateable);
            }

            IPositionUpdateable integrable = spaceObject as IPositionUpdateable;

            if (integrable != null)
            {
                PositionUpdater.Remove(integrable);
            }

            Entity entity = spaceObject as Entity;

            if (entity != null)
            {
                BufferedStates.Remove(entity);
            }

            IDeferredEventCreator deferredEventCreator = spaceObject as IDeferredEventCreator;

            if (deferredEventCreator != null)
            {
                DeferredEventDispatcher.RemoveEventCreator(deferredEventCreator);
            }

            IDeferredEventCreatorOwner deferredEventCreatorOwner = spaceObject as IDeferredEventCreatorOwner;

            if (deferredEventCreatorOwner != null)
            {
                DeferredEventDispatcher.RemoveEventCreator(deferredEventCreatorOwner.EventCreator);
            }

            //Updateable stages.
            IDuringForcesUpdateable duringForcesUpdateable = spaceObject as IDuringForcesUpdateable;

            if (duringForcesUpdateable != null)
            {
                DuringForcesUpdateables.Remove(duringForcesUpdateable);
            }

            IBeforeNarrowPhaseUpdateable beforeNarrowPhaseUpdateable = spaceObject as IBeforeNarrowPhaseUpdateable;

            if (beforeNarrowPhaseUpdateable != null)
            {
                BeforeNarrowPhaseUpdateables.Remove(beforeNarrowPhaseUpdateable);
            }

            IBeforeSolverUpdateable beforeSolverUpdateable = spaceObject as IBeforeSolverUpdateable;

            if (beforeSolverUpdateable != null)
            {
                BeforeSolverUpdateables.Remove(beforeSolverUpdateable);
            }


            IBeforePositionUpdateUpdateable beforePositionUpdateUpdateable = spaceObject as IBeforePositionUpdateUpdateable;

            if (beforePositionUpdateUpdateable != null)
            {
                BeforePositionUpdateUpdateables.Remove(beforePositionUpdateUpdateable);
            }

            IEndOfTimeStepUpdateable endOfStepUpdateable = spaceObject as IEndOfTimeStepUpdateable;

            if (endOfStepUpdateable != null)
            {
                EndOfTimeStepUpdateables.Remove(endOfStepUpdateable);
            }

            IEndOfFrameUpdateable endOfFrameUpdateable = spaceObject as IEndOfFrameUpdateable;

            if (endOfFrameUpdateable != null)
            {
                EndOfFrameUpdateables.Remove(endOfFrameUpdateable);
            }

            spaceObject.Space = null;
            spaceObject.OnRemovalFromSpace(this);
        }
 internal ReceiveAssignmentEventArgs(Solver solver)
     : base(solver)
 {
 }
Exemplo n.º 45
0
    /**
     *
     * Secret Santa problem in Google CP Solver.
     *
     * From Ruby Quiz Secret Santa
     * http://www.rubyquiz.com/quiz2.html
     * """
     * Honoring a long standing tradition started by my wife's dad, my friends
     * all play a Secret Santa game around Christmas time. We draw names and
     * spend a week sneaking that person gifts and clues to our identity. On the
     * last night of the game, we get together, have dinner, share stories, and,
     * most importantly, try to guess who our Secret Santa was. It's a crazily
     * fun way to enjoy each other's company during the holidays.
     *
     * To choose Santas, we use to draw names out of a hat. This system was
     * tedious, prone to many 'Wait, I got myself...' problems. This year, we
     * made a change to the rules that further complicated picking and we knew
     * the hat draw would not stand up to the challenge. Naturally, to solve
     * this problem, I scripted the process. Since that turned out to be more
     * interesting than I had expected, I decided to share.
     *
     * This weeks Ruby Quiz is to implement a Secret Santa selection script.
     * *  Your script will be fed a list of names on STDIN.
     * ...
     * Your script should then choose a Secret Santa for every name in the list.
     * Obviously, a person cannot be their own Secret Santa. In addition, my friends
     * no longer allow people in the same family to be Santas for each other and your
     * script should take this into account.
     * """
     *
     *  Comment: This model skips the file input and mail parts. We
     *        assume that the friends are identified with a number from 1..n,
     *        and the families is identified with a number 1..num_families.
     *
     * Also see http://www.hakank.org/or-tools/secret_santa.py
     * Also see http://www.hakank.org/or-tools/secret_santa2.cs
     *
     */
    private static void Solve()
    {
        Solver solver = new Solver("SecretSanta");

        int[] family = { 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 4, 4 };
        int   n      = family.Length;

        Console.WriteLine("n = {0}", n);

        IEnumerable <int> RANGE = Enumerable.Range(0, n);

        //
        // Decision variables
        //
        IntVar[] x = solver.MakeIntVarArray(n, 0, n - 1, "x");


        //
        // Constraints
        //
        solver.Add(x.AllDifferent());

        // Can't be one own"s Secret Santa
        // (i.e. ensure that there are no fix-point in the array.)
        foreach (int i in RANGE)
        {
            solver.Add(x[i] != i);
        }


        // No Secret Santa to a person in the same family
        foreach (int i in RANGE)
        {
            solver.Add(solver.MakeIntConst(family[i]) != family.Element(x[i]));
        }

        //
        // Search
        //
        DecisionBuilder db = solver.MakePhase(x,
                                              Solver.INT_VAR_SIMPLE,
                                              Solver.INT_VALUE_SIMPLE);

        solver.NewSearch(db);

        while (solver.NextSolution())
        {
            Console.Write("x:  ");
            foreach (int i in RANGE)
            {
                Console.Write(x[i].Value() + " ");
            }
            Console.WriteLine();
        }

        Console.WriteLine("\nSolutions: {0}", solver.Solutions());
        Console.WriteLine("WallTime: {0}ms", solver.WallTime());
        Console.WriteLine("Failures: {0}", solver.Failures());
        Console.WriteLine("Branches: {0} ", solver.Branches());

        solver.EndSearch();
    }
 internal ReceiveAssignmentEventArgs(Solver solver, Assignment assignment)
     : base(solver)
 {
     Assignment = assignment;
 }
Exemplo n.º 47
0
    /**
     *
     * Ski assignment in Google CP Solver.
     *
     * From   Jeffrey Lee Hellrung, Jr.:
     * PIC 60, Fall 2008 Final Review, December 12, 2008
     * http://www.math.ucla.edu/~jhellrun/course_files/Fall%25202008/PIC%252060%2520-%2520Data%2520Structures%2520and%2520Algorithms/final_review.pdf
     * """
     * 5. Ski Optimization! Your job at Snapple is pleasant but in the winter
     * you've decided to become a ski bum. You've hooked up with the Mount
     * Baldy Ski Resort. They'll let you ski all winter for free in exchange
     * for helping their ski rental shop with an algorithm to assign skis to
     * skiers. Ideally, each skier should obtain a pair of skis whose height
     * matches his or her own height exactly. Unfortunately, this is generally
     * not possible. We define the disparity between a skier and his or her
     * skis to be the absolute value of the difference between the height of
     * the skier and the pair of skis. Our objective is to find an assignment
     * of skis to skiers that minimizes the sum of the disparities.
     * ...
     * Illustrate your algorithm by explicitly filling out the A[i, j] table
     * for the following sample data:
     *  - Ski heights  : 1, 2, 5, 7, 13, 21.
     *  - Skier heights: 3, 4, 7, 11, 18.
     * """
     *
     * Also see http://www.hakank.org/or-tools/ski_assignment.py
     *
     *
     */
    private static void Solve()
    {
        Solver solver = new Solver("SkiAssignment");

        //
        // Data
        //
        int num_skis   = 6;
        int num_skiers = 5;

        int[] ski_heights   = { 1, 2, 5, 7, 13, 21 };
        int[] skier_heights = { 3, 4, 7, 11, 18 };

        //
        // Decision variables
        //
        IntVar[] x = solver.MakeIntVarArray(num_skiers, 0, num_skis - 1, "x");

        //
        // Constraints
        //
        solver.Add(x.AllDifferent());

        IntVar[] z_tmp = new IntVar[num_skiers];
        for (int i = 0; i < num_skiers; i++)
        {
            z_tmp[i] = (ski_heights.Element(x[i]) - skier_heights[i]).Abs().Var();
        }

        //    IntVar z = solver.MakeIntVar(0, ski_heights.Sum(), "z");
        //    solver.Add(z_tmp.Sum() == z);
        // The direct cast from IntExpr to IntVar is potentially faster than
        // the above code.
        IntVar z = z_tmp.Sum().VarWithName("z");

        //
        // Objective
        //
        OptimizeVar obj = z.Minimize(1);

        //
        // Search
        //
        DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.INT_VALUE_DEFAULT);

        solver.NewSearch(db, obj);

        while (solver.NextSolution())
        {
            Console.Write("z: {0} x: ", z.Value());
            for (int i = 0; i < num_skiers; i++)
            {
                Console.Write(x[i].Value() + " ");
            }
            Console.WriteLine();
        }

        Console.WriteLine("\nSolutions: {0}", solver.Solutions());
        Console.WriteLine("WallTime: {0}ms", solver.WallTime());
        Console.WriteLine("Failures: {0}", solver.Failures());
        Console.WriteLine("Branches: {0} ", solver.Branches());

        solver.EndSearch();
    }
Exemplo n.º 48
0
        public void Part1(string data, string newLine, int result)
        {
            var groups = Parser.ParseGroups(data, newLine);

            Assert.That(Solver.Part1(groups), Is.EqualTo(result));
        }
Exemplo n.º 49
0
    /**
     *
     * Post office problem.
     *
     * Problem statement:
     * http://www-128.ibm.com/developerworks/linux/library/l-glpk2/
     *
     * From Winston 'Operations Research: Applications and Algorithms':
     * """
     * A post office requires a different number of full-time employees working
     * on different days of the week [summarized below]. Union rules state that
     * each full-time employee must work for 5 consecutive days and then receive
     * two days off. For example, an employee who works on Monday to Friday
     * must be off on Saturday and Sunday. The post office wants to meet its
     * daily requirements using only full-time employees. Minimize the number
     * of employees that must be hired.
     *
     * To summarize the important information about the problem:
     *
     * Every full-time worker works for 5 consecutive days and takes 2 days off
     * - Day 1 (Monday): 17 workers needed
     * - Day 2 : 13 workers needed
     * - Day 3 : 15 workers needed
     * - Day 4 : 19 workers needed
     * - Day 5 : 14 workers needed
     * - Day 6 : 16 workers needed
     * - Day 7 (Sunday) : 11 workers needed
     *
     * The post office needs to minimize the number of employees it needs
     * to hire to meet its demand.
     * """
     *
     * Also see http://www.hakank.org/or-tools/post_office_problem2.py
     *
     */
    private static void Solve()
    {
        Solver solver = new Solver("PostOfficeProblem2");

        //
        // Data
        //

        // days 0..6, monday 0
        int n = 7;

        int[] need = { 17, 13, 15, 19, 14, 16, 11 };

        // Total cost for the 5 day schedule.
        // Base cost per day is 100.
        // Working saturday is 100 extra
        // Working sunday is 200 extra.
        int[] cost = { 500, 600, 800, 800, 800, 800, 700 };

        //
        // Decision variables
        //

        // No. of workers starting at day i
        IntVar[] x = solver.MakeIntVarArray(n, 0, 100, "x");

        IntVar total_cost  = x.ScalProd(cost).Var();
        IntVar num_workers = x.Sum().Var();

        //
        // Constraints
        //
        for (int i = 0; i < n; i++)
        {
            IntVar s = (from j in Enumerable.Range(0, n) where j != (i + 5) % n &&
                        j != (i + 6) % n select x[j])
                       .ToArray()
                       .Sum()
                       .Var();
            solver.Add(s >= need[i]);
        }

        // Add a limit for the cost
        solver.Add(total_cost <= 20000);

        //

        // objective
        //
        //
        OptimizeVar obj = total_cost.Minimize(100);

        //
        // Search
        //
        DecisionBuilder db =
            solver.MakePhase(x, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_MIN_VALUE);

        solver.NewSearch(db, obj);

        while (solver.NextSolution())
        {
            Console.WriteLine("num_workers: {0}", num_workers.Value());
            Console.WriteLine("total_cost: {0}", total_cost.Value());
            Console.Write("x: ");
            for (int i = 0; i < n; i++)
            {
                Console.Write(x[i].Value() + " ");
            }
            Console.WriteLine("\n");
        }

        Console.WriteLine("\nSolutions: {0}", solver.Solutions());
        Console.WriteLine("WallTime: {0}ms", solver.WallTime());
        Console.WriteLine("Failures: {0}", solver.Failures());
        Console.WriteLine("Branches: {0} ", solver.Branches());

        solver.EndSearch();
    }
Exemplo n.º 50
0
    // [END data_model]
    public static void Main()
    {
        // [START data]
        DataModel data = new DataModel();
        // [END data]
        // [END program_part1]

        // [START solver]
        // Create the linear solver with the CBC backend.
        Solver solver = Solver.CreateSolver("MultipleKnapsackMip", "CBC");

        // [END solver]

        // [START program_part2]
        // [START variables]
        Variable[,] x = new Variable[data.NumItems, data.NumBins];
        for (int i = 0; i < data.NumItems; i++)
        {
            for (int j = 0; j < data.NumBins; j++)
            {
                x[i, j] = solver.MakeIntVar(0, 1, $"x_{i}_{j}");
            }
        }
        // [END variables]

        // [START constraints]
        for (int i = 0; i < data.NumItems; ++i)
        {
            Constraint constraint = solver.MakeConstraint(0, 1, "");
            for (int j = 0; j < data.NumBins; ++j)
            {
                constraint.SetCoefficient(x[i, j], 1);
            }
        }

        for (int j = 0; j < data.NumBins; ++j)
        {
            Constraint constraint = solver.MakeConstraint(0, data.BinCapacities[j], "");
            for (int i = 0; i < data.NumItems; ++i)
            {
                constraint.SetCoefficient(x[i, j], DataModel.Weights[i]);
            }
        }
        // [END constraints]

        // [START objective]
        Objective objective = solver.Objective();

        for (int i = 0; i < data.NumItems; ++i)
        {
            for (int j = 0; j < data.NumBins; ++j)
            {
                objective.SetCoefficient(x[i, j], DataModel.Values[i]);
            }
        }
        objective.SetMaximization();
        // [END objective]

        // [START solve]
        Solver.ResultStatus resultStatus = solver.Solve();
        // [END solve]

        // [START print_solution]
        // Check that the problem has an optimal solution.
        if (resultStatus != Solver.ResultStatus.OPTIMAL)
        {
            Console.WriteLine("The problem does not have an optimal solution!");
            return;
        }
        Console.WriteLine("Total packed value: " + solver.Objective().Value());
        double TotalWeight = 0.0;

        for (int j = 0; j < data.NumBins; ++j)
        {
            double BinWeight = 0.0;
            double BinValue  = 0.0;
            Console.WriteLine("Bin " + j);
            for (int i = 0; i < data.NumItems; ++i)
            {
                if (x[i, j].SolutionValue() == 1)
                {
                    Console.WriteLine($"Item {i} weight: {DataModel.Weights[i]} values: {DataModel.Values[i]}");
                    BinWeight += DataModel.Weights[i];
                    BinValue  += DataModel.Values[i];
                }
            }
            Console.WriteLine("Packed bin weight: " + BinWeight);
            Console.WriteLine("Packed bin value: " + BinValue);
            TotalWeight += BinWeight;
        }
        Console.WriteLine("Total packed weight: " + TotalWeight);
        // [END print_solution]
    }
Exemplo n.º 51
0
        static void Main(string[] args)
        {
            Solver solver = Solver.CreateSolver("SimpleLpProgram", "GLOP_LINEAR_PROGRAMMING");

            //Variables x, y > 0
            Variable x = solver.MakeNumVar(0.0, double.PositiveInfinity, "x");
            Variable y = solver.MakeNumVar(0.0, double.PositiveInfinity, "y");

            Console.WriteLine("Liczba zmiennych = " + solver.NumVariables());

            // Constraints:
            // 6x + 3y >= 120
            // x + 3y >= 60
            // 9x + y >= 36
            // 6x + 6y >= 180
            Constraint ct1a = solver.MakeConstraint(120, double.PositiveInfinity, "ct1a");

            ct1a.SetCoefficient(x, 6);
            ct1a.SetCoefficient(y, 3);

            Constraint ct2a = solver.MakeConstraint(60, double.PositiveInfinity, "ct2a");

            ct2a.SetCoefficient(x, 1);
            ct2a.SetCoefficient(y, 3);

            Constraint ct3a = solver.MakeConstraint(36, double.PositiveInfinity, "ct3a");

            ct3a.SetCoefficient(x, 9);
            ct3a.SetCoefficient(y, 1);

            Constraint ct4a = solver.MakeConstraint(180, double.PositiveInfinity, "ct4a");

            ct4a.SetCoefficient(x, 6);
            ct4a.SetCoefficient(y, 6);

            Console.WriteLine("Liczba ograniczeń = " + solver.NumConstraints());

            // Objective function: 1.2x + 1.8y => min
            Objective objectiveA = solver.Objective();

            objectiveA.SetCoefficient(x, 1.2);
            objectiveA.SetCoefficient(y, 1.8);
            objectiveA.SetMinimization();

            solver.Solve();

            Console.WriteLine("-----------------------");
            Console.WriteLine("Rozwiązanie punkt 1:");
            Console.WriteLine("Wartość funkcji celu: = " + solver.Objective().Value());
            Console.WriteLine("Nalezy wyprodukowac = " + (int)Math.Ceiling(x.SolutionValue()) + " P1 produktow");
            Console.WriteLine("Nalezy wyprodukowac = " + (int)Math.Ceiling(y.SolutionValue()) + " P2 produktow");
            Console.WriteLine("-----------------------");

            Console.WriteLine("Rozwiazanie punkt 2:");
            // Constraints:
            // 6x + 3y < 240
            // x + 3y >= 60
            // 9x + y >= 36
            // 6x + 6y >= 180
            Constraint ct1b = solver.MakeConstraint(double.NegativeInfinity, 240, "ct1b");

            ct1b.SetCoefficient(x, 6);
            ct1b.SetCoefficient(y, 3);

            Constraint ct2b = solver.MakeConstraint(60, double.PositiveInfinity, "ct2b");

            ct2b.SetCoefficient(x, 1);
            ct2b.SetCoefficient(y, 3);

            Constraint ct3b = solver.MakeConstraint(36, double.PositiveInfinity, "ct3b");

            ct3b.SetCoefficient(x, 9);
            ct3b.SetCoefficient(y, 1);

            Constraint ct4b = solver.MakeConstraint(180, double.PositiveInfinity, "ct4b");

            ct4b.SetCoefficient(x, 6);
            ct4b.SetCoefficient(y, 6);

            // Objective function: 1.2x + 1.8y => min
            Objective objectiveB = solver.Objective();

            objectiveB.SetCoefficient(x, 1.2);
            objectiveB.SetCoefficient(y, 1.8);
            objectiveB.SetMinimization();

            solver.Solve();
            Console.WriteLine("Nalezy wyprodukowac = " + (int)Math.Ceiling(x.SolutionValue()) + " P1 produktow");
            Console.WriteLine("Nalezy wyprodukowac = " + (int)Math.Ceiling(y.SolutionValue()) + " P2 produktow");

            Console.WriteLine("Nie zmieni sie rozwiazanie, jezeli nie mozna podawac wiecej niz 240 jednostek witaminy A");
            Console.WriteLine("-----------------------");
        }
Exemplo n.º 52
0
 public void InitializeDamage(Solver solver, bool areaEffect, int range, MagicSchool magicSchool, SpellData spellData)
 {
     InitializeDamage(solver, areaEffect, range, magicSchool, spellData, 1, 1, 0);
 }
Exemplo n.º 53
0
        public void InitializeDamage(Solver solver, bool areaEffect, int range, MagicSchool magicSchool, int cost, float minDamage, float maxDamage, float spellDamageCoefficient, float periodicDamage, float dotDamageCoefficient, float hitProcs, float castProcs, float dotDuration)
        {
            Stats                  baseStats          = solver.BaseStats;
            MageTalents            mageTalents        = solver.MageTalents;
            CalculationOptionsMage calculationOptions = solver.CalculationOptions;

            AreaEffect        = areaEffect;
            AreaEffectDot     = areaEffect;
            MaximumAOETargets = 10;
            int manaReduction = (int)baseStats.SpellsManaCostReduction;

            if (manaReduction == 405)
            {
                // Shard of Woe hax
                manaReduction = 205;
            }
            BaseCost               = Math.Max(cost - manaReduction, 0);
            MagicSchool            = magicSchool;
            Ticks                  = hitProcs;
            CastProcs              = castProcs;
            CastProcs2             = castProcs;
            BaseMinDamage          = minDamage;
            BaseMaxDamage          = maxDamage;
            SpellDamageCoefficient = spellDamageCoefficient;
            BasePeriodicDamage     = periodicDamage;
            DotDamageCoefficient   = dotDamageCoefficient;
            DotDuration            = dotDuration;

            BaseDirectDamageModifier = 1.0f;
            BaseDotDamageModifier    = 1.0f;
            BaseCostModifier         = 1.0f;

            float baseCostAmplifier = calculationOptions.EffectCostMultiplier;

            if (mageTalents.EnduringWinter > 0)
            {
                BaseCostModifier -= 0.03f * mageTalents.EnduringWinter + (mageTalents.EnduringWinter == 3 ? 0.01f : 0.00f);
            }
            BaseCostAmplifier = baseCostAmplifier;

            float baseInterruptProtection = baseStats.InterruptProtection;

            baseInterruptProtection += 0.23f * mageTalents.BurningSoul + (mageTalents.BurningSoul == 3 ? 0.01f : 0.0f);
            BaseInterruptProtection  = baseInterruptProtection;

            float realResistance;

            switch (MagicSchool)
            {
            case MagicSchool.Arcane:
                BaseSpellModifier         = solver.BaseArcaneSpellModifier;
                BaseAdditiveSpellModifier = solver.BaseArcaneAdditiveSpellModifier;
                BaseCritRate     = solver.BaseArcaneCritRate;
                CritBonus        = solver.BaseArcaneCritBonus;
                HitRate          = solver.BaseArcaneHitRate;
                ThreatMultiplier = solver.ArcaneThreatMultiplier;
                realResistance   = calculationOptions.ArcaneResist;
                IgniteFactor     = 0;
                break;

            case MagicSchool.Fire:
                BaseSpellModifier         = solver.BaseFireSpellModifier;
                BaseAdditiveSpellModifier = solver.BaseFireAdditiveSpellModifier;
                BaseCritRate     = solver.BaseFireCritRate;
                CritBonus        = solver.BaseFireCritBonus;
                HitRate          = solver.BaseFireHitRate;
                ThreatMultiplier = solver.FireThreatMultiplier;
                realResistance   = calculationOptions.FireResist;
                IgniteFactor     = solver.IgniteFactor;
                break;

            case MagicSchool.FrostFire:
                BaseSpellModifier         = solver.BaseFrostFireSpellModifier;
                BaseAdditiveSpellModifier = solver.BaseFrostFireAdditiveSpellModifier;
                BaseCritRate     = solver.BaseFrostFireCritRate;
                CritBonus        = solver.BaseFrostFireCritBonus;
                HitRate          = solver.BaseFrostFireHitRate;
                ThreatMultiplier = solver.FrostFireThreatMultiplier;
                if (calculationOptions.FireResist == -1)
                {
                    realResistance = calculationOptions.FrostResist;
                }
                else if (calculationOptions.FrostResist == -1)
                {
                    realResistance = calculationOptions.FireResist;
                }
                else
                {
                    realResistance = Math.Min(calculationOptions.FireResist, calculationOptions.FrostResist);
                }
                Range        = range;
                IgniteFactor = solver.IgniteFactor;
                break;

            case MagicSchool.Frost:
                BaseSpellModifier         = solver.BaseFrostSpellModifier;
                BaseAdditiveSpellModifier = solver.BaseFrostAdditiveSpellModifier;
                BaseCritRate     = solver.BaseFrostCritRate;
                CritBonus        = solver.BaseFrostCritBonus;
                HitRate          = solver.BaseFrostHitRate;
                ThreatMultiplier = solver.FrostThreatMultiplier;
                realResistance   = calculationOptions.FrostResist;
                IgniteFactor     = 0;
                break;

            case MagicSchool.Nature:
                BaseSpellModifier         = solver.BaseNatureSpellModifier;
                BaseAdditiveSpellModifier = solver.BaseNatureAdditiveSpellModifier;
                BaseCritRate     = solver.BaseNatureCritRate;
                CritBonus        = solver.BaseNatureCritBonus;
                HitRate          = solver.BaseNatureHitRate;
                ThreatMultiplier = solver.NatureThreatMultiplier;
                realResistance   = calculationOptions.NatureResist;
                Range            = range;
                IgniteFactor     = 0;
                break;

            case MagicSchool.Shadow:
                BaseSpellModifier         = solver.BaseShadowSpellModifier;
                BaseAdditiveSpellModifier = solver.BaseShadowAdditiveSpellModifier;
                BaseCritRate     = solver.BaseShadowCritRate;
                CritBonus        = solver.BaseShadowCritBonus;
                HitRate          = solver.BaseShadowHitRate;
                ThreatMultiplier = solver.ShadowThreatMultiplier;
                realResistance   = calculationOptions.ShadowResist;
                Range            = range;
                IgniteFactor     = 0;
                break;

            case MagicSchool.Holy:
            default:
                BaseSpellModifier         = solver.BaseHolySpellModifier;
                BaseAdditiveSpellModifier = solver.BaseHolyAdditiveSpellModifier;
                BaseCritRate     = solver.BaseHolyCritRate;
                CritBonus        = solver.BaseHolyCritBonus;
                HitRate          = solver.BaseHolyHitRate;
                ThreatMultiplier = solver.HolyThreatMultiplier;
                realResistance   = calculationOptions.HolyResist;
                Range            = range;
                IgniteFactor     = 0;
                break;
            }

            NonHSCritRate = baseStats.SpellCritOnTarget;

            int playerLevel = calculationOptions.PlayerLevel;
            int targetLevel;

            if (areaEffect)
            {
                targetLevel = calculationOptions.AoeTargetLevel;
                float hitRate = ((targetLevel <= playerLevel + 2) ? (0.96f - (targetLevel - playerLevel) * 0.01f) : (0.94f - (targetLevel - playerLevel - 2) * 0.11f)) + solver.BaseSpellHit;
                if (hitRate > Spell.MaxHitRate)
                {
                    hitRate = Spell.MaxHitRate;
                }
                HitRate = hitRate;
            }
            else
            {
                targetLevel = calculationOptions.TargetLevel;
            }

            RealResistance      = realResistance;
            PartialResistFactor = (realResistance == -1) ? 0 : (1 - StatConversion.GetAverageResistance(playerLevel, targetLevel, realResistance, baseStats.SpellPenetration));
        }
Exemplo n.º 54
0
    /**
     *
     * Solves the Quasigroup Completion problem.
     * See http://www.hakank.org/or-tools/quasigroup_completion.py
     *
     */
    private static void Solve()
    {
        Solver solver = new Solver("QuasigroupCompletion");

        //
        // data
        //
        Console.WriteLine("Problem:");
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                Console.Write(problem[i, j] + " ");
            }
            Console.WriteLine();
        }
        Console.WriteLine();


        //
        // Decision variables
        //
        IntVar[,] x = solver.MakeIntVarMatrix(n, n, 1, n, "x");
        IntVar[] x_flat = x.Flatten();

        //
        // Constraints
        //
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (problem[i, j] > X)
                {
                    solver.Add(x[i, j] == problem[i, j]);
                }
            }
        }

        //
        // rows and columns must be different
        //

        // rows
        for (int i = 0; i < n; i++)
        {
            IntVar[] row = new IntVar[n];
            for (int j = 0; j < n; j++)
            {
                row[j] = x[i, j];
            }
            solver.Add(row.AllDifferent());
        }

        // columns
        for (int j = 0; j < n; j++)
        {
            IntVar[] col = new IntVar[n];
            for (int i = 0; i < n; i++)
            {
                col[i] = x[i, j];
            }
            solver.Add(col.AllDifferent());
        }


        //
        // Search
        //
        DecisionBuilder db = solver.MakePhase(x_flat,
                                              Solver.INT_VAR_SIMPLE,
                                              Solver.ASSIGN_MIN_VALUE);

        solver.NewSearch(db);

        int sol = 0;

        while (solver.NextSolution())
        {
            sol++;
            Console.WriteLine("Solution #{0} ", sol + " ");
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    Console.Write("{0} ", x[i, j].Value());
                }
                Console.WriteLine();
            }

            Console.WriteLine();
        }

        Console.WriteLine("\nSolutions: {0}", solver.Solutions());
        Console.WriteLine("WallTime: {0}ms", solver.WallTime());
        Console.WriteLine("Failures: {0}", solver.Failures());
        Console.WriteLine("Branches: {0} ", solver.Branches());

        solver.EndSearch();
    }
Exemplo n.º 55
0
    /**
     *
     * Rogo puzzle solver.
     *
     * From http://www.rogopuzzle.co.nz/
     * """
     * The object is to collect the biggest score possible using a given
     * number of steps in a loop around a grid. The best possible score
     * for a puzzle is given with it, so you can easily check that you have
     * solved the puzzle. Rogo puzzles can also include forbidden squares,
     * which must be avoided in your loop.
     * """
     *
     * Also see Mike Trick:
     * "Operations Research, Sudoko, Rogo, and Puzzles"
     * http://mat.tepper.cmu.edu/blog/?p=1302
     *
     *
     * Also see, http://www.hakank.org/or-tools/rogo2.py
     * though this model differs in a couple of central points
     * which makes it much faster:
     *
     * - it use a table (
     * AllowedAssignments) with the valid connections
     * - instead of two coordinates arrays, it use a single path array
     *
     */
    private static void Solve()
    {
        Solver solver = new Solver("Rogo2");

        Console.WriteLine("\n");
        Console.WriteLine("**********************************************");
        Console.WriteLine("    {0}", problem_name);
        Console.WriteLine("**********************************************\n");

        //
        // Data
        //
        int B = -1;

        Console.WriteLine("Rows: {0} Cols: {1} Max Steps: {2}", rows, cols, max_steps);

        int[] problem_flatten = problem.Cast <int>().ToArray();
        int   max_point       = problem_flatten.Max();
        int   max_sum         = problem_flatten.Sum();

        Console.WriteLine("max_point: {0} max_sum: {1} best: {2}", max_point, max_sum, best);

        IEnumerable <int> STEPS  = Enumerable.Range(0, max_steps);
        IEnumerable <int> STEPS1 = Enumerable.Range(0, max_steps - 1);

        // the valid connections, to be used with AllowedAssignments
        IntTupleSet valid_connections = ValidConnections(rows, cols);

        //
        // Decision variables
        //
        IntVar[] path       = solver.MakeIntVarArray(max_steps, 0, rows * cols - 1, "path");
        IntVar[] points     = solver.MakeIntVarArray(max_steps, 0, best, "points");
        IntVar   sum_points = points.Sum().VarWithName("sum_points");

        //
        // Constraints
        //

        foreach (int s in STEPS)
        {
            // calculate the points (to maximize)
            solver.Add(points[s] == problem_flatten.Element(path[s]));

            // ensure that there are no black cells in
            // the path
            solver.Add(problem_flatten.Element(path[s]) != B);
        }

        solver.Add(path.AllDifferent());

        // valid connections
        foreach (int s in STEPS1)
        {
            solver.Add(new IntVar[] { path[s], path[s + 1] }.AllowedAssignments(valid_connections));
        }
        // around the corner
        solver.Add(new IntVar[] { path[max_steps - 1], path[0] }.AllowedAssignments(valid_connections));

        // Symmetry breaking
        for (int s = 1; s < max_steps; s++)
        {
            solver.Add(path[0] < path[s]);
        }

        //
        // Objective
        //
        OptimizeVar obj = sum_points.Maximize(1);

        //
        // Search
        //
        DecisionBuilder db = solver.MakePhase(path, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT);

        solver.NewSearch(db, obj);

        while (solver.NextSolution())
        {
            Console.WriteLine("sum_points: {0}", sum_points.Value());
            Console.Write("path: ");
            foreach (int s in STEPS)
            {
                Console.Write("{0} ", path[s].Value());
            }
            Console.WriteLine();
            Console.WriteLine("(Adding 1 to coords...)");
            int[,] sol = new int[rows, cols];
            foreach (int s in STEPS)
            {
                int p = (int)path[s].Value();
                int x = (int)(p / cols);
                int y = (int)(p % cols);
                Console.WriteLine("{0,2},{1,2} ({2} points)", x + 1, y + 1, points[s].Value());
                sol[x, y] = 1;
            }
            Console.WriteLine("\nThe path is marked by 'X's:");
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    String p = sol[i, j] == 1 ? "X" : " ";
                    String q = problem[i, j] == B ? "B" : problem[i, j] == 0 ? "." : problem[i, j].ToString();
                    Console.Write("{0,2}{1} ", q, p);
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }

        Console.WriteLine("\nSolutions: {0}", solver.Solutions());
        Console.WriteLine("WallTime: {0}ms", solver.WallTime());
        Console.WriteLine("Failures: {0}", solver.Failures());
        Console.WriteLine("Branches: {0} ", solver.Branches());

        solver.EndSearch();
    }
Exemplo n.º 56
0
    /**
     *
     * Simple regular expression.
     *
     * My last name (Kjellerstrand) is quite often misspelled
     * in ways that this regular expression shows:
     *   k(je|ä)ll(er|ar)?(st|b)r?an?d
     *
     * This model generates all the words that can be construed
     * by this regular expression.
     *
     *
     * Also see http://www.hakank.org/or-tools/regex.py
     *
     */
    private static void Solve(int n, List <String> res)
    {
        Solver solver = new Solver("RegexGeneration");

        Console.WriteLine("\nn: {0}", n);

        // The DFS (for regular)
        int n_states      = 11;
        int input_max     = 12;
        int initial_state = 1; // 0 is for the failing state

        int[] accepting_states = { 12 };

        // The DFA
        int[,] transition_fn =
        {
            // 1 2 3 4 5 6 7 8 9 0 1 2   //
            { 0, 2, 3, 0, 0, 0, 0, 0, 0,  0,  0,  0 }, //  1 k
            { 0, 0, 0, 4, 0, 0, 0, 0, 0,  0,  0,  0 }, //  2 je
            { 0, 0, 0, 4, 0, 0, 0, 0, 0,  0,  0,  0 }, //  3 ä
            { 0, 0, 0, 0, 5, 6, 7, 8, 0,  0,  0,  0 }, //  4 ll
            { 0, 0, 0, 0, 0, 0, 7, 8, 0,  0,  0,  0 }, //  5 er
            { 0, 0, 0, 0, 0, 0, 7, 8, 0,  0,  0,  0 }, //  6 ar
            { 0, 0, 0, 0, 0, 0, 0, 0, 9, 10,  0,  0 }, //  7 st
            { 0, 0, 0, 0, 0, 0, 0, 0, 9, 10,  0,  0 }, //  8 b
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,  0,  0 }, //  9 r
            { 0, 0, 0, 0, 0, 0, 0, 0, 0,  0, 11, 12 }, // 10 a
            { 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0, 12 }, // 11 n
                                                       // 12 d
        };

        // Name of the states
        String[] s = { "k", "je", "ä", "ll", "er", "ar", "st", "b", "r", "a", "n", "d" };

        //
        // Decision variables
        //
        IntVar[] x = solver.MakeIntVarArray(n, 1, input_max, "x");

        //
        // Constraints
        //
        MyRegular(solver, x, n_states, input_max, transition_fn, initial_state, accepting_states);

        //
        // Search
        //
        DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);

        solver.NewSearch(db);

        while (solver.NextSolution())
        {
            List <String> res2 = new List <String>();
            // State 1 (the start state) is not included in the
            // state array (x) so we add it first.
            res2.Add(s[0]);
            for (int i = 0; i < n; i++)
            {
                res2.Add(s[x[i].Value() - 1]);
            }
            res.Add(String.Join("", res2.ToArray()));
        }

        Console.WriteLine("\nSolutions: {0}", solver.Solutions());
        Console.WriteLine("WallTime: {0}ms", solver.WallTime());
        Console.WriteLine("Failures: {0}", solver.Failures());
        Console.WriteLine("Branches: {0} ", solver.Branches());

        solver.EndSearch();
    }
Exemplo n.º 57
0
        /// <summary>
        /// 24通りから任意のロジック組み合わせを取得
        /// </summary>
        /// <param name="solver"></param>
        /// <returns></returns>
        public LogicDelegates[] GetLogicCombination(Solver solver)
        {
            LogicDelegates[] logics = new LogicDelegates[4];
            logics[0] = solver.ShareCandLogic;
            logics[1] = solver.PairLogic;
            logics[2] = solver.CrossLogic;
            logics[3] = solver.TripleLogic;

            switch (combinationNo)
            {
            case 1:
                logics[0] = solver.PairLogic;      //双子
                logics[1] = solver.ShareCandLogic; //共有
                logics[2] = solver.TripleLogic;    //三つ子
                logics[3] = solver.CrossLogic;     //対角
                break;

            case 2:
                logics[0] = solver.PairLogic;      //双子
                logics[1] = solver.ShareCandLogic; //共有
                logics[2] = solver.CrossLogic;     //対角
                logics[3] = solver.TripleLogic;    //三つ子
                break;

            case 3:
                logics[0] = solver.PairLogic;      //双子
                logics[1] = solver.TripleLogic;    //三つ子
                logics[2] = solver.ShareCandLogic; //共有
                logics[3] = solver.CrossLogic;     //対角
                break;

            case 4:
                logics[0] = solver.PairLogic;      //双子
                logics[1] = solver.TripleLogic;    //三つ子
                logics[2] = solver.CrossLogic;     //対角
                logics[3] = solver.ShareCandLogic; //共有
                break;

            case 5:
                logics[0] = solver.PairLogic;      //双子
                logics[1] = solver.CrossLogic;     //対角
                logics[2] = solver.ShareCandLogic; //共有
                logics[3] = solver.TripleLogic;    //三つ子
                break;

            case 6:
                logics[0] = solver.PairLogic;      //双子
                logics[1] = solver.CrossLogic;     //対角
                logics[2] = solver.TripleLogic;    //三つ子
                logics[3] = solver.ShareCandLogic; //共有
                break;

            case 7:
                logics[0] = solver.ShareCandLogic; //共有
                logics[1] = solver.PairLogic;      //双子
                logics[2] = solver.TripleLogic;    //三つ子
                logics[3] = solver.CrossLogic;     //対角
                break;

            case 8:
                logics[0] = solver.ShareCandLogic; //共有
                logics[1] = solver.PairLogic;      //双子
                logics[2] = solver.CrossLogic;     //対角
                logics[3] = solver.TripleLogic;    //三つ子
                break;

            case 9:
                logics[0] = solver.ShareCandLogic; //共有
                logics[1] = solver.TripleLogic;    //三つ子
                logics[2] = solver.PairLogic;      //双子
                logics[3] = solver.CrossLogic;     //対角
                break;

            case 10:
                logics[0] = solver.ShareCandLogic; //共有
                logics[1] = solver.TripleLogic;    //三つ子
                logics[2] = solver.CrossLogic;     //対角
                logics[3] = solver.PairLogic;      //双子
                break;

            case 11:
                logics[0] = solver.ShareCandLogic; //共有
                logics[1] = solver.CrossLogic;     //対角
                logics[2] = solver.PairLogic;      //双子
                logics[3] = solver.TripleLogic;    //三つ子
                break;

            case 12:
                logics[0] = solver.ShareCandLogic; //共有
                logics[1] = solver.CrossLogic;     //対角
                logics[2] = solver.TripleLogic;    //三つ子
                logics[3] = solver.PairLogic;      //双子
                break;

            case 13:
                logics[0] = solver.TripleLogic;    //三つ子
                logics[1] = solver.PairLogic;      //双子
                logics[2] = solver.ShareCandLogic; //共有
                logics[3] = solver.CrossLogic;     //対角
                break;

            case 14:
                logics[0] = solver.TripleLogic;    //三つ子
                logics[1] = solver.PairLogic;      //双子
                logics[2] = solver.CrossLogic;     //対角
                logics[3] = solver.ShareCandLogic; //共有
                break;

            case 15:
                logics[0] = solver.TripleLogic;    //三つ子
                logics[1] = solver.ShareCandLogic; //共有
                logics[2] = solver.PairLogic;      //双子
                logics[3] = solver.CrossLogic;     //対角
                break;

            case 16:
                logics[0] = solver.TripleLogic;    //三つ子
                logics[1] = solver.ShareCandLogic; //共有
                logics[2] = solver.CrossLogic;     //対角
                logics[3] = solver.PairLogic;      //双子
                break;

            case 17:
                logics[0] = solver.TripleLogic;    //三つ子
                logics[1] = solver.CrossLogic;     //対角
                logics[2] = solver.PairLogic;      //双子
                logics[3] = solver.ShareCandLogic; //共有
                break;

            case 18:
                logics[0] = solver.TripleLogic;    //三つ子
                logics[1] = solver.CrossLogic;     //対角
                logics[2] = solver.ShareCandLogic; //共有
                logics[3] = solver.PairLogic;      //双子
                break;

            case 19:
                logics[0] = solver.CrossLogic;     //対角
                logics[1] = solver.PairLogic;      //双子
                logics[2] = solver.ShareCandLogic; //共有
                logics[3] = solver.TripleLogic;    //三つ子
                break;

            case 20:
                logics[0] = solver.CrossLogic;     //対角
                logics[1] = solver.PairLogic;      //双子
                logics[2] = solver.TripleLogic;    //三つ子
                logics[3] = solver.ShareCandLogic; //共有
                break;

            case 21:
                logics[0] = solver.CrossLogic;     //対角
                logics[1] = solver.ShareCandLogic; //共有
                logics[2] = solver.PairLogic;      //双子
                logics[3] = solver.TripleLogic;    //三つ子
                break;

            case 22:
                logics[0] = solver.CrossLogic;     //対角
                logics[1] = solver.ShareCandLogic; //共有
                logics[2] = solver.TripleLogic;    //三つ子
                logics[3] = solver.PairLogic;      //双子
                break;

            case 23:
                logics[0] = solver.CrossLogic;     //対角
                logics[1] = solver.TripleLogic;    //三つ子
                logics[2] = solver.PairLogic;      //双子
                logics[3] = solver.ShareCandLogic; //共有
                break;

            case 24:
                logics[0] = solver.CrossLogic;     //対角
                logics[1] = solver.TripleLogic;    //三つ子
                logics[2] = solver.ShareCandLogic; //共有
                logics[3] = solver.PairLogic;      //双子
                break;
            }

            return(logics);
        }
Exemplo n.º 58
0
        public Tuple <double, ItemList> getOre(double refineRate, int trit, int pyer, int mex, int iso, int nocx, int zyd, int mega, int morph)
        {
            Solver solver = new Solver("Ore Solver", Solver.GLOP_LINEAR_PROGRAMMING);

            Dictionary <Variable, ore> vars = new Dictionary <Variable, ore>();

            foreach (ore ore in Prices.Keys)
            {
                vars.Add(solver.MakeIntVar(0.0, double.PositiveInfinity, ore.name), ore);
            }

            Objective end = solver.Objective();

            end.SetMinimization();

            foreach (KeyValuePair <Variable, ore> var in vars)
            {
                end.SetCoefficient(var.Key, Prices[var.Value]);
            }

            Constraint tritConst = solver.MakeConstraint((double)trit, double.PositiveInfinity);

            foreach (KeyValuePair <Variable, ore> var in vars)
            {
                tritConst.SetCoefficient(var.Key, var.Value.Tritanium * refineRate);
            }

            Constraint pyerConst = solver.MakeConstraint((double)pyer, double.PositiveInfinity);

            foreach (KeyValuePair <Variable, ore> var in vars)
            {
                pyerConst.SetCoefficient(var.Key, var.Value.Pyerite * refineRate);
            }

            Constraint mexConst = solver.MakeConstraint((double)mex, double.PositiveInfinity);

            foreach (KeyValuePair <Variable, ore> var in vars)
            {
                mexConst.SetCoefficient(var.Key, var.Value.Mexallon * refineRate);
            }

            Constraint isoConst = solver.MakeConstraint((double)iso, double.PositiveInfinity);

            foreach (KeyValuePair <Variable, ore> var in vars)
            {
                isoConst.SetCoefficient(var.Key, var.Value.Isogen * refineRate);
            }

            Constraint nocxConst = solver.MakeConstraint((double)nocx, double.PositiveInfinity);

            foreach (KeyValuePair <Variable, ore> var in vars)
            {
                nocxConst.SetCoefficient(var.Key, var.Value.Nocxium * refineRate);
            }

            Constraint zydConst = solver.MakeConstraint((double)zyd, double.PositiveInfinity);

            foreach (KeyValuePair <Variable, ore> var in vars)
            {
                zydConst.SetCoefficient(var.Key, var.Value.Zydrine * refineRate);
            }

            Constraint megaConst = solver.MakeConstraint((double)mega, double.PositiveInfinity);

            foreach (KeyValuePair <Variable, ore> var in vars)
            {
                megaConst.SetCoefficient(var.Key, var.Value.Megacyte * refineRate);
            }

            Constraint morphConst = solver.MakeConstraint((double)morph, double.PositiveInfinity);

            foreach (KeyValuePair <Variable, ore> var in vars)
            {
                morphConst.SetCoefficient(var.Key, var.Value.Morphite * refineRate);
            }

            solver.Solve();

            double price = end.Value();

            ItemList list = new ItemList();

            foreach (KeyValuePair <Variable, ore> var in vars)
            {
                if (var.Key.SolutionValue() > 0)
                {
                    list.Add(var.Value.invType, (int)var.Key.SolutionValue());
                }
            }

            return(new Tuple <double, ItemList>(price, list));
        }
Exemplo n.º 59
0
        public static void TestPacket(Options options)
        {
            Console.WriteLine("Parsing firewall rules...");
            WindowsFirewall firewall = new WindowsFirewall
            {
                BlockByDefault = options.FirewallBlockByDefault,
                Rules          = WindowsFirewallRuleParser.Parse(File.ReadAllText(options.FirewallFilepath), '\t').ToList()
            };

            int  protocolNumber;
            bool anyProtocol = false;

            if (!NetworkProtocol.TryGetProtocolNumber(options.Protocol, out protocolNumber))
            {
                if (string.Equals("Any", options.Protocol, StringComparison.InvariantCultureIgnoreCase))
                {
                    anyProtocol = true;
                }
                else
                {
                    protocolNumber = int.Parse(options.Protocol);
                }
            }

            WindowsFirewallPacket packet = new WindowsFirewallPacket
            {
                SourceAddress   = IPAddress.Parse(options.SourceAddress),
                SourcePort      = string.Equals("Any", options.SourcePort, StringComparison.InvariantCultureIgnoreCase) ? null : (int?)int.Parse(options.SourcePort),
                DestinationPort = string.Equals("Any", options.DestinationPort, StringComparison.InvariantCultureIgnoreCase) ? null : (int?)int.Parse(options.DestinationPort),
                Protocol        = anyProtocol ? null : (int?)protocolNumber
            };

            Console.WriteLine("Checking action of firewall on packet...");
            using (var ctx = new Context())
            {
                Solver s          = ctx.MkSolver();
                var    packetVars = new WindowsFirewallPacketVariables(ctx);
                s.Assert(packet.Matches(ctx, packetVars));
                s.Check();

                if (s.Model.Eval(firewall.Allows(ctx, packetVars)).IsTrue)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Packet is allowed by firewall.");
                    Console.ResetColor();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Packet is NOT allowed by firewall.");
                    Console.ResetColor();
                }

                List <WindowsFirewallRule> ruleMatches = firewall.GetMatches(ctx, packetVars, s.Model).ToList();
                if (!ruleMatches.Any())
                {
                    Console.WriteLine("No firewall rules match the test packet.");
                    return;
                }

                Console.WriteLine();
                Console.WriteLine("Firewall rules matching the test packet:");
                Console.WriteLine("-------------------------------------------------------------------------");
                Console.WriteLine("| Action | Rule Name                                                    |");
                Console.WriteLine("-------------------------------------------------------------------------");
                foreach (WindowsFirewallRule rule in ruleMatches)
                {
                    Console.WriteLine(
                        $"| {(rule.Allow ? "Allow" : "Block"), 6} " +
                        $"| {rule.Name.Substring(0, Math.Min(rule.Name.Length, 60)), -60} |");
                }

                Console.WriteLine("-------------------------------------------------------------------------");
            }
        }
Exemplo n.º 60
0
    static void Main()
    {
        // Data.
        // [START data_model]
        int[,] costs =
        {
            { 90, 80, 75, 70 }, { 35, 85, 55, 65 }, { 125, 95, 90, 95 }, { 45, 110, 95, 115 }, { 50, 100, 90, 100 },
        };
        int numWorkers = costs.GetLength(0);
        int numTasks   = costs.GetLength(1);
        // [END data_model]

        // Model.
        // [START model]
        Solver solver = Solver.CreateSolver("SCIP");

        // [END model]

        // Variables.
        // [START variables]
        // x[i, j] is an array of 0-1 variables, which will be 1
        // if worker i is assigned to task j.
        Variable[,] x = new Variable[numWorkers, numTasks];
        for (int i = 0; i < numWorkers; ++i)
        {
            for (int j = 0; j < numTasks; ++j)
            {
                x[i, j] = solver.MakeIntVar(0, 1, $"worker_{i}_task_{j}");
            }
        }
        // [END variables]

        // Constraints
        // [START constraints]
        // Each worker is assigned to at most one task.
        for (int i = 0; i < numWorkers; ++i)
        {
            Constraint constraint = solver.MakeConstraint(0, 1, "");
            for (int j = 0; j < numTasks; ++j)
            {
                constraint.SetCoefficient(x[i, j], 1);
            }
        }
        // Each task is assigned to exactly one worker.
        for (int j = 0; j < numTasks; ++j)
        {
            Constraint constraint = solver.MakeConstraint(1, 1, "");
            for (int i = 0; i < numWorkers; ++i)
            {
                constraint.SetCoefficient(x[i, j], 1);
            }
        }
        // [END constraints]

        // Objective
        // [START objective]
        Objective objective = solver.Objective();

        for (int i = 0; i < numWorkers; ++i)
        {
            for (int j = 0; j < numTasks; ++j)
            {
                objective.SetCoefficient(x[i, j], 1);
            }
        }
        objective.SetMinimization();
        // [END objective]

        // Solve
        // [START solve]
        Solver.ResultStatus resultStatus = solver.Solve();
        // [END solve]

        // Print solution.
        // [START print_solution]
        // Check that the problem has a feasible solution.
        if (resultStatus == Solver.ResultStatus.OPTIMAL || resultStatus == Solver.ResultStatus.FEASIBLE)
        {
            Console.WriteLine($"Total cost: {solver.Objective().Value()}\n");
            for (int i = 0; i < numWorkers; ++i)
            {
                for (int j = 0; j < numTasks; ++j)
                {
                    // Test if x[i, j] is 0 or 1 (with tolerance for floating point
                    // arithmetic).
                    if (x[i, j].SolutionValue() > 0.5)
                    {
                        Console.WriteLine($"Worker {i} assigned to task {j}. Cost: {costs[i, j]}");
                    }
                }
            }
        }
        else
        {
            Console.WriteLine("No solution found.");
        }
        // [END print_solution]
    }