public void MaximalPreservativeCrossoverApplyTest() {
      TestRandom random = new TestRandom();
      Permutation parent1, parent2, expected, actual;
      // The following test is based on an example from Larranaga, 1999. Genetic Algorithms for the Traveling Salesman Problem.
      random.Reset();
      random.IntNumbers = new int[] { 3, 2 };
      parent1 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 2, 3, 4, 5, 6, 7 });
      Assert.IsTrue(parent1.Validate());
      parent2 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 1, 3, 5, 7, 6, 4, 2, 0 });
      Assert.IsTrue(parent2.Validate());
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 1, 0, 2, 3, 4, 5, 7, 6 });
      Assert.IsTrue(expected.Validate());
      actual = MaximalPreservativeCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));

      // perform a test when the two permutations are of unequal length
      random.Reset();
      bool exceptionFired = false;
      try {
        MaximalPreservativeCrossover.Apply(random, new Permutation(PermutationTypes.RelativeUndirected, 8), new Permutation(PermutationTypes.RelativeUndirected, 6));
      }
      catch (System.ArgumentException) {
        exceptionFired = true;
      }
      Assert.IsTrue(exceptionFired);
    }
    public void CyclicCrossoverApplyTest() {
      TestRandom random = new TestRandom();
      Permutation parent1, parent2, expected, actual;
      // The following test is based on an example from Larranaga, P. et al. 1999. Genetic Algorithms for the Travelling Salesman Problem: A Review of Representations and Operators. Artificial Intelligence Review, 13
      random.Reset();
      random.DoubleNumbers = new double[] { 0.9 };
      parent1 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 2, 3, 4, 5, 6, 7 });
      Assert.IsTrue(parent1.Validate());
      parent2 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 1, 3, 5, 7, 6, 4, 2, 0 });
      Assert.IsTrue(parent2.Validate());
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 5, 3, 6, 4, 2, 7 });
      Assert.IsTrue(expected.Validate());
      actual = CyclicCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));

      // perform a test when the two permutations are of unequal length
      random.Reset();
      bool exceptionFired = false;
      try {
        CyclicCrossover.Apply(random, new Permutation(PermutationTypes.RelativeUndirected, 8), new Permutation(PermutationTypes.RelativeUndirected, 6));
      }
      catch (System.ArgumentException) {
        exceptionFired = true;
      }
      Assert.IsTrue(exceptionFired);
    }
    public void TestPermutationEqualityComparer() {
      PermutationEqualityComparer comparer = new PermutationEqualityComparer();
      Permutation p = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 3, 2, 0, 1, 4 });
      Permutation q = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 1, 0, 2, 3, 4 });
      Assert.IsTrue(comparer.Equals(p, q));
      Assert.IsTrue(comparer.GetHashCode(p) == comparer.GetHashCode(q));
      Permutation p2 = new Permutation(PermutationTypes.RelativeDirected, new int[] { 2, 3, 4, 1, 0 });
      Permutation q2 = new Permutation(PermutationTypes.RelativeDirected, new int[] { 1, 0, 2, 3, 4 });
      Assert.IsTrue(comparer.Equals(p2, q2));
      Assert.IsTrue(comparer.GetHashCode(p2) == comparer.GetHashCode(q2));

      Assert.IsFalse(comparer.Equals(p, q2));
      Assert.IsFalse(comparer.Equals(p2, q));

      Permutation p3 = new Permutation(PermutationTypes.Absolute, new int[] { 2, 3, 0, 4, 1 });
      Permutation q3 = new Permutation(PermutationTypes.Absolute, new int[] { 2, 3, 0, 4, 1 });
      Assert.IsTrue(comparer.Equals(p3, q3));
      Assert.IsTrue(comparer.GetHashCode(p3) == comparer.GetHashCode(q3));

      Assert.IsFalse(comparer.Equals(p3, q));
      Assert.IsFalse(comparer.Equals(p2, q3));

      Permutation p4 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 3, 2, 0, 1, 4, 5 });
      Assert.IsFalse(comparer.Equals(p, p4));
      Assert.IsFalse(comparer.Equals(p4, q));
    }
    public void EdgeRecombinationCrossoverApplyTest() {
      TestRandom random = new TestRandom();
      Permutation parent1, parent2, expected, actual;
      // The following test is based on an example from Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, pp. 54-55
      random.Reset();
      random.IntNumbers = new int[] { 0 };
      random.DoubleNumbers = new double[] { 0.5, 0, 0, 0 };
      parent1 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 });
      Assert.IsTrue(parent1.Validate());
      parent2 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 8, 2, 6, 7, 1, 5, 4, 0, 3 });
      Assert.IsTrue(parent2.Validate());
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 4, 5, 1, 7, 6, 2, 8, 3 });
      Assert.IsTrue(expected.Validate());
      actual = EdgeRecombinationCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));

      // perform a test when the two permutations are of unequal length
      random.Reset();
      bool exceptionFired = false;
      try {
        EdgeRecombinationCrossover.Apply(random, new Permutation(PermutationTypes.RelativeUndirected, 8), new Permutation(PermutationTypes.RelativeUndirected, 6));
      }
      catch (System.ArgumentException) {
        exceptionFired = true;
      }
      Assert.IsTrue(exceptionFired);
    }
    public void OrderCrossover2ApplyTest() {
      TestRandom random = new TestRandom();
      Permutation parent1, parent2, expected, actual;
      // The following test is based on an example from Affenzeller, M. et al. 2009. Genetic Algorithms and Genetic Programming - Modern Concepts and Practical Applications. CRC Press. p. 135.
      random.Reset();
      random.IntNumbers = new int[] { 5, 7 };
      parent1 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
      Assert.IsTrue(parent1.Validate());
      parent2 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 2, 5, 6, 0, 9, 1, 3, 8, 4, 7 });
      Assert.IsTrue(parent2.Validate());
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 2, 0, 9, 1, 3, 5, 6, 7, 8, 4 });
      Assert.IsTrue(expected.Validate());
      actual = OrderCrossover2.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));

      // perform a test when the two permutations are of unequal length
      random.Reset();
      bool exceptionFired = false;
      try {
        OrderCrossover.Apply(random, new Permutation(PermutationTypes.RelativeUndirected, 8), new Permutation(PermutationTypes.RelativeUndirected, 6));
      }
      catch (System.ArgumentException) {
        exceptionFired = true;
      }
      Assert.IsTrue(exceptionFired);
    }
Example #6
0
        static double BruteForce()
        {
            var map = new Dictionary<Permutation, List<double>>();
            double i = 345;
            while (true)
            {
                var value = i*i*i;
                var permutation = new Permutation(value);
                if(!map.ContainsKey(permutation))
                {
                    map.Add(permutation, new List<double>());
                }
                map[permutation].Add(value);
                if(map[permutation].Count == 5)
                {
                    foreach (var num in map[permutation])
                    {
                        Console.Out.WriteLine(num);
                    }
                    return map[permutation].Min();
                }
                i++;
            }

            return 0;
        }
  public override void Main() {
    DateTime start = DateTime.UtcNow;

    QuadraticAssignmentProblem qap;
    if (vars.Contains("qap")) qap = vars.qap;
    else {
      var provider = new DreznerQAPInstanceProvider();
      var instance = provider.GetDataDescriptors().Single(x => x.Name == "dre56");
      var data = provider.LoadData(instance);
      qap = new QuadraticAssignmentProblem();
      qap.Load(data);
      vars.qap = qap;
    }

    const uint seed = 0;
    const int popSize = 100;
    const int generations = 1000;
    const double mutationRate = 0.05;

    var random = new MersenneTwister(seed);
    var population = new Permutation[popSize];
    var qualities = new double[popSize];
    var nextGen = new Permutation[popSize];
    var nextQual = new double[popSize];

    var qualityChart = new DataTable("Quality Chart");
    var qualityRow = new DataRow("Best Quality");
    qualityChart.Rows.Add(qualityRow);
    vars.qualityChart = qualityChart;

    for (int i = 0; i < popSize; i++) {
      population[i] = new Permutation(PermutationTypes.Absolute, qap.Weights.Rows, random);
      qualities[i] = QAPEvaluator.Apply(population[i], qap.Weights, qap.Distances);
    }
    var bestQuality = qualities.Min();
    var bestQualityGeneration = 0;

    for (int g = 0; g < generations; g++) {
      var parents = population.SampleProportional(random, 2 * popSize, qualities, windowing: true, inverseProportional: true).ToArray();
      for (int i = 0; i < popSize; i++) {
        nextGen[i] = PartiallyMatchedCrossover.Apply(random, parents[i * 2], parents[i * 2 + 1]);
        if (random.NextDouble() < mutationRate) Swap2Manipulator.Apply(random, nextGen[i]);
        nextQual[i] = QAPEvaluator.Apply(nextGen[i], qap.Weights, qap.Distances);
        if (nextQual[i] < bestQuality) {
          bestQuality = nextQual[i];
          bestQualityGeneration = g;
        }
      }
      qualityRow.Values.Add(bestQuality);
      Array.Copy(nextGen, population, popSize);
      Array.Copy(nextQual, qualities, popSize);
    }

    vars.elapsed = new TimeSpanValue(DateTime.UtcNow - start);
    vars.bestQuality = bestQuality;
    vars.bestQualityFoundAt = bestQualityGeneration;
  }
 public void CanCreateInversionsFromPermutation(int[] inv, int[] idx)
 {
     var q = new Permutation(idx);
     var p = q.ToInversions();
     Assert.AreEqual(inv.Length, p.Length);
     for (var i = 0; i < q.Dimension; i++)
     {
         Assert.AreEqual(inv[i], p[i]);
     }
 }
Example #9
0
        static string BruteForce()
        {
            var map = new Dictionary<Permutation, List<int>>();
            for (var i = 1000; i < 10000; i++)
            {
                if (MathUtils.IsPrime(i))
                {
                    var digits = MathUtils.ConvertToDigits(i);
                    {
                        var permutation = new Permutation(digits);
                        if (!map.ContainsKey(permutation))
                        {
                            map.Add(permutation, new List<int>());
                        }
                        var value = map[permutation];
                        value.Add(i);
                    }
                }
            }

            foreach (var result in map.Where(x => x.Value.Count >= 3))
            {
                var value = result.Value;
                if (value.Count == 3)
                {
                    if (IsArithmeticSequence(value))
                    {
                        Print(value);
                    }
                }
                else
                {
                    for (int i = 0; i < value.Count - 3; i++)
                    {
                        for (int j = i + 1; j < value.Count - 1; j++)
                        {
                            
                            for (int k = j + 1; k < value.Count; k++)
                            {
                                var list = new List<int>();
                                list.Add(value[i]);
                                list.Add(value[j]);
                                list.Add(value[k]);
                                if (IsArithmeticSequence(list))
                                {
                                    Print(list);
                                }
                            }
                        }
                    }
                }
            }

            return "";
        }
        public void CanCreatePermutationFromInversions(int[] inv, int[] idx)
        {
            var p = Permutation.FromInversions(inv);
            var q = new Permutation(idx);

            Assert.AreEqual(q.Dimension, p.Dimension);
            for (int i = 0; i < q.Dimension; i++)
            {
                Assert.AreEqual(q[i], p[i]);
            }
        }
        public override BaseVariable[] CreateVariables()
        {
            BaseVariable[] variables = new BaseVariable[Problema.NumberOfVariables];

            for (int var = 0; var < Problema.NumberOfVariables; var++)
            {
                variables[var] = new Permutation(Problema.GetLength(var));
            }

            return variables;
        }
Example #12
0
        public void CanInvertPermutation([Values(new[] { 0 }, new[] { 0, 1, 2, 3, 4, 5 }, new[] { 5, 4, 3, 2, 1, 0 }, new[] { 0, 4, 3, 2, 1, 5 }, new[] { 0, 3, 2, 1, 4, 5 })] int[] idx)
        {
            var p = new Permutation(idx);
            var pinv = p.Inverse();

            Assert.AreEqual(p.Dimension, pinv.Dimension);
            for (var i = 0; i < p.Dimension; i++)
            {
                Assert.AreEqual(i, pinv[p[i]]);
                Assert.AreEqual(i, p[pinv[i]]);
            }
        }
Example #13
0
 public static bool PermutationIsEqualByPosition(Permutation p1, Permutation p2) {
   bool equal = (p1.Length == p2.Length);
   if (equal) {
     for (int i = 0; i < p1.Length; i++) {
       if (p1[i] != p2[i]) {
         equal = false;
         break;
       }
     }
   }
   return equal;
 }
 public void CanCreateInversionsFromPermutation(
     [Values(new[] { 0 }, new[] { 0, 1, 2, 3, 4, 5 }, new[] { 5, 4, 3, 3, 4, 5 }, new[] { 0, 4, 3, 3, 4, 5 }, new[] { 0, 3, 2, 3, 4, 5 }, new[] { 2, 2, 2, 4, 4 })] int[] inv, 
     [Values(new[] { 0 }, new[] { 0, 1, 2, 3, 4, 5 }, new[] { 5, 4, 3, 2, 1, 0 }, new[] { 0, 4, 3, 2, 1, 5 }, new[] { 0, 3, 2, 1, 4, 5 }, new[] { 1, 2, 0, 4, 3 })] int[] idx)
 {
     var q = new Permutation(idx);
     var p = q.ToInversions();
     Assert.AreEqual(inv.Length, p.Length);
     for (var i = 0; i < q.Dimension; i++)
     {
         Assert.AreEqual(inv[i], p[i]);
     }
 }
        public void CanCreatePermutationFromInversions(
            [Values(new[] { 0 }, new[] { 0, 1, 2, 3, 4, 5 }, new[] { 5, 4, 3, 3, 4, 5 }, new[] { 0, 4, 3, 3, 4, 5 }, new[] { 0, 3, 2, 3, 4, 5 }, new[] { 2, 2, 2, 4, 4 })] int[] inv, 
            [Values(new[] { 0 }, new[] { 0, 1, 2, 3, 4, 5 }, new[] { 5, 4, 3, 2, 1, 0 }, new[] { 0, 4, 3, 2, 1, 5 }, new[] { 0, 3, 2, 1, 4, 5 }, new[] { 1, 2, 0, 4, 3 })] int[] idx)
        {
            var p = Permutation.FromInversions(inv);
            var q = new Permutation(idx);

            Assert.AreEqual(q.Dimension, p.Dimension);
            for (var i = 0; i < q.Dimension; i++)
            {
                Assert.AreEqual(q[i], p[i]);
            }
        }
    public void CosaCrossoverApplyTest() {
      TestRandom random = new TestRandom();
      Permutation parent1, parent2, expected, actual;
      // The following test is based on an example from Wendt, O. 1994. COSA: COoperative Simulated Annealing - Integration von Genetischen Algorithmen und Simulated Annealing am Beispiel der Tourenplanung. Dissertation Thesis. IWI Frankfurt.
      random.Reset();
      random.IntNumbers = new int[] { 1 };
      parent1 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 5, 2, 4, 3 });
      Assert.IsTrue(parent1.Validate());
      parent2 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 3, 0, 2, 1, 4, 5 });
      Assert.IsTrue(parent2.Validate());
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 4, 2, 5, 3 });
      Assert.IsTrue(expected.Validate());
      actual = CosaCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));
      // The following test is not based on published examples
      random.Reset();
      random.IntNumbers = new int[] { 4 };
      parent1 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 2, 3, 4, 5, 6, 7 });
      Assert.IsTrue(parent1.Validate());
      parent2 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 1, 3, 5, 7, 6, 4, 2, 0 });
      Assert.IsTrue(parent2.Validate());
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 7, 6, 5, 3, 4, 2, 1, 0 });
      Assert.IsTrue(expected.Validate());
      actual = CosaCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));
      // The following test is not based on published examples
      random.Reset();
      random.IntNumbers = new int[] { 5 };
      parent1 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
      Assert.IsTrue(parent1.Validate());
      parent2 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 4, 3, 5, 1, 0, 9, 7, 2, 8, 6 });
      Assert.IsTrue(parent2.Validate());
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 7, 6, 2, 3, 4, 5, 1, 0, 9, 8 });
      Assert.IsTrue(expected.Validate());
      actual = CosaCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));

      // perform a test when the two permutations are of unequal length
      random.Reset();
      bool exceptionFired = false;
      try {
        CosaCrossover.Apply(random, new Permutation(PermutationTypes.RelativeUndirected, 8), new Permutation(PermutationTypes.RelativeUndirected, 6));
      }
      catch (System.ArgumentException) {
        exceptionFired = true;
      }
      Assert.IsTrue(exceptionFired);
    }
    public void TranslocationManipulatorApplyTest() {
      TestRandom random = new TestRandom();
      Permutation parent, expected;
      // The following test is based on an example from Larranaga, P. et al. 1999. Genetic Algorithms for the Travelling Salesman Problem: A Review of Representations and Operators. Artificial Intelligence Review, 13, p. 24
      random.Reset();
      random.IntNumbers = new int[] { 2, 4, 4 };
      parent = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 2, 3, 4, 5, 6, 7 });
      Assert.IsTrue(parent.Validate());

      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 5, 6, 2, 3, 4, 7 });
      Assert.IsTrue(expected.Validate());
      TranslocationManipulator.Apply(random, parent);
      Assert.IsTrue(parent.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, parent));
    }
    public void InversionManipulatorApplyTest() {
      TestRandom random = new TestRandom();
      Permutation parent, expected;
      // The following test is based on an example from Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, pp. 46-47
      random.Reset();
      random.IntNumbers = new int[] { 1, 4 };
      parent = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 });
      Assert.IsTrue(parent.Validate());

      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 4, 3, 2, 1, 5, 6, 7, 8 });
      Assert.IsTrue(expected.Validate());
      InversionManipulator.Apply(random, parent);
      Assert.IsTrue(parent.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, parent));
    }
    public void Swap3ManipulatorApplyTest() {
      TestRandom random = new TestRandom();
      Permutation parent, expected;
      // Test manipulator
      random.Reset();
      random.IntNumbers = new int[] { 1, 3, 6 };
      random.DoubleNumbers = new double[] { 0 };
      parent = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 });
      Assert.IsTrue(parent.Validate());

      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 3, 2, 6, 4, 5, 1, 7, 8 });
      Assert.IsTrue(expected.Validate());
      Swap3Manipulator.Apply(random, parent);
      Assert.IsTrue(parent.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, parent));
    }
 public void UniformLikeCrossoverApplyTest() {
   // test from the paper
   IRandom random = new TestRandom(new int[] { 0 }, new double[] { 0.2, 0.7, 0.2, 0.2 }); // TODO: Initialize to an appropriate value
   Permutation parent1 = new Permutation(PermutationTypes.Absolute,
     new int[] { 3, 2, 0, 7, 5, 4, 1, 6 });
   Assert.IsTrue(parent1.Validate());
   Permutation parent2 = new Permutation(PermutationTypes.Absolute,
     new int[] { 5, 0, 4, 7, 1, 3, 2, 6 });
   Assert.IsTrue(parent2.Validate());
   Permutation expected = new Permutation(PermutationTypes.Absolute,
     new int[] { 3, 0, 4, 7, 5, 2, 1, 6 });
   Assert.IsTrue(expected.Validate());
   Permutation actual;
   actual = UniformLikeCrossover.Apply(random, parent1, parent2);
   Assert.IsTrue(actual.Validate());
   Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));
 }
Example #21
0
 public void GetTranspositionsTest()
 {
     var permutation = new Permutation();
     var input = new[] {
         new BaseNode<int, object>(0, 0),
         new BaseNode<int, object>(0, 1),
         new BaseNode<int, object>(0, 2),
         new BaseNode<int, object>(0, 3),
         new BaseNode<int, object>(0, 4),
         new BaseNode<int, object>(0, 5)
     };
     var transpositions = permutation.GetTranspositions(input, 0).Select(item => string.Join(",", item.Select(node => node.Key))).ToList();
     int n = input.Length;
     int expectedCount = Factorial(n);
     int i = 0;
     foreach (var transposition in transpositions)
     {
         _testOutputHelper.WriteLine("[Transpositions:{0}], [{1}]", i, transposition);
         i++;
     }
     Assert.Equal(expectedCount, transpositions.Count);
 }
            /// <summary>
            ///     Constructor for use by synthesizing factory.
            /// </summary>
            /// <param name="leastItemInSequence">
            ///     The lowest value that starts off <cref>OriginalMonotonicIncreasingSequence</cref>
            /// </param>
            /// <param name="nonNegativeDeltas">
            ///     Sequence of non-negative deltas that will be used to build up
            ///     <cref>OriginalMonotonicIncreasingSequence</cref>
            /// </param>
            /// <param name="permutation">
            ///     A permutation that is used to shuffle <cref>OriginalMonotonicIncreasingSequence</cref> to give
            ///     <cref>PermutedSequence</cref>
            /// </param>
            public TestCase(Int32 leastItemInSequence,
                IEnumerable<Int32> nonNegativeDeltas, Permutation<Int32> permutation)
            {
                var originalMonotonicIncreasingSequence = new List<Int32>();

                var runningSum = leastItemInSequence;

                foreach (var nonNegativeDelta in nonNegativeDeltas)
                {
                    originalMonotonicIncreasingSequence.Add(runningSum);
                    runningSum += nonNegativeDelta;
                }

                originalMonotonicIncreasingSequence.Add(runningSum);

                OriginalMonotonicIncreasingSequence = originalMonotonicIncreasingSequence;

                PermutedSequence = permutation(originalMonotonicIncreasingSequence);
            }
Example #23
0
 public PotvinEncoding(IVRPProblemInstance instance)
     : base(instance)
 {
     Unrouted          = new List <int>();
     VehicleAssignment = new Permutation(PermutationTypes.Absolute, instance.Vehicles.Value);
 }
Example #24
0
			private static long GetPermutationPriority(Permutation permutation)
			{
				// Prioritize the remaining elements in terms of mandatories, then entity/value balance, then deep/shallow.
				// 1) An unbalanced mandatory constraint is given highest priority, outweighing all other concerns.
				//    For a shallow, prefer a mapping towards the mandatory role. For a deep mapping, prefer a mapping
				//    away from the mandatory role.
				// 2) A double mandatory is given next priority, outweighing all entity/value issues
				// 3) A mapping between an entity and value gets the next highest priority
				// 4) A mapping between two entities is next (value-to-value gets no points)
				// 5) A deep mapping has a higher priority than an shallow mapping, but does not override
				//    any other concerns.
				FactTypeMappingList mappings = permutation.Mappings;
				int mappingCount = mappings.Count;
				const long deepMappingValue = 1;
				long balancedEntityValue = mappingCount + 1;
				long unbalancedEntityValue = balancedEntityValue * mappingCount + 1;
				long balancedMandatoryValue = unbalancedEntityValue * mappingCount + 1;
				long unbalancedMandatoryValue = unbalancedEntityValue * mappingCount + 1;
				long retVal = 0;
				for (int i = 0; i < mappingCount; ++i)
				{
					FactTypeMapping mapping = mappings[i];
					// Completely ignore implied mandatory. If both are implied mandatory, then this ranks the same as non-mandatory
					bool fromMandatory = mapping.FromRoleExplicitlyMandatory;
					bool toMandatory = mapping.TowardsRoleExplicitlyMandatory;
					bool deepMapping = mapping.MappingDepth == MappingDepth.Deep;
					if (fromMandatory)
					{
						if (toMandatory)
						{
							retVal += balancedMandatoryValue;
						}
						else if (deepMapping)
						{
							retVal += unbalancedMandatoryValue;
						}
					}
					else if (toMandatory && !deepMapping)
					{
						retVal += unbalancedMandatoryValue;
					}
					if (mapping.FromValueType)
					{
						if (!mapping.TowardsValueType)
						{
							retVal += unbalancedEntityValue;
						}
					}
					else if (!mapping.TowardsValueType)
					{
						retVal += balancedEntityValue; // Entity to entity gets higher priority than value/value
					}
					if (deepMapping)
					{
						if (mapping.IsFromPreferredIdentifier)
						{
							retVal -= deepMappingValue; // Discourage deep mapping away from the preferred identifier
						}
						else
						{
							retVal += deepMappingValue;
						}
					}
				}
				return retVal;
			}
Example #25
0
 protected PotvinEncoding(PotvinEncoding original, Cloner cloner)
     : base(original, cloner)
 {
     this.Unrouted          = new List <int>(original.Unrouted);
     this.VehicleAssignment = cloner.Clone <Permutation>(original.VehicleAssignment);
 }
 public void PermuteMatrixRowsThrowsInvalidOperationException()
 {
     var matrixp = DiagonalMatrix.OfArray(TestData2D["Singular3x3"]);
     var permutation = new Permutation(new[] {2, 0, 1});
     Assert.That(() => matrixp.PermuteRows(permutation), Throws.InvalidOperationException);
 }
 protected abstract double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix);
 // network specific, AUTOGENERATED
 static void inputPermutation(float[] activationOfPreviousLayer, NeuronPropertiesIdentityVariable neuronProperties)
 {
     Permutation.identity(activationOfPreviousLayer, ref neuronProperties.permutatedInput);
 }
 // network specific, AUTOGENERATED
 static void inputPermutation(float[] activationOfPreviousLayer, NeuronPropertiesPermutationExp neuronProperties)
 {
     Permutation.permutation(activationOfPreviousLayer, ref neuronProperties.permutatedInput, neuronProperties.srcIndices);
 }
        public static PotvinEncoding ApplyManipulation(IRandom random, PotvinEncoding individual, IPickupAndDeliveryProblemInstance pdp, bool allowInfeasible)
        {
            PotvinEncoding result = null;

            int selectedIndex = SelectRandomTourBiasedByLength(random, individual, pdp);

            if (selectedIndex >= 0)
            {
                bool performed = false;
                Tour route1    = individual.Tours[selectedIndex];

                if (route1.Stops.Count > 0)
                {
                    //randomize customer selection
                    Permutation perm = new Permutation(PermutationTypes.Absolute, route1.Stops.Count, random);
                    int         customer1Position = 0;

                    while (customer1Position < route1.Stops.Count)
                    {
                        performed = false;

                        int customer1 = route1.Stops[perm[customer1Position]];
                        int customer2 = -1;

                        for (int i = 0; i < individual.Tours.Count; i++)
                        {
                            if (i != selectedIndex)
                            {
                                Tour tour = individual.Tours[i];
                                for (int customer2Position = 0; customer2Position < tour.Stops.Count; customer2Position++)
                                {
                                    customer2 = tour.Stops[customer2Position];

                                    if (pdp.GetPickupDeliveryLocation(customer1) != customer2)
                                    {
                                        result = ReplacePair(individual, pdp, customer2, customer1, allowInfeasible);
                                        if (result != null)
                                        {
                                            individual = result;

                                            route1    = individual.Tours[selectedIndex];
                                            performed = true;
                                            break;
                                        }
                                    }
                                }
                            }

                            if (performed)
                            {
                                break;
                            }
                        }

                        if (!performed)
                        {
                            customer1Position++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            return(result);
        }
Example #31
0
        /// <summary>
        /// Find a maximum transveral (zero-free diagonal). Seed optionally selects a
        /// randomized algorithm.
        /// </summary>
        /// <param name="A">column-compressed matrix</param>
        /// <param name="seed">0: natural, -1: reverse, randomized otherwise</param>
        /// <returns>row and column matching, size m+n</returns>
        public static int[] Generate(SymbolicColumnStorage A, int seed)
        {
            int i, j, k, p, n2 = 0, m2 = 0;

            int[] jimatch, w, cheap, js, iss, ps, Cp, q;

            int n = A.ColumnCount;
            int m = A.RowCount;

            int[] Ap = A.ColumnPointers;
            int[] Ai = A.RowIndices;

            //[jmatch [0..m-1]; imatch [0..n-1]]
            w = jimatch = new int[m + n];  // allocate result

            for (k = 0, j = 0; j < n; j++) // count nonempty rows and columns
            {
                n2 += (Ap[j] < Ap[j + 1]) ? 1 : 0;
                for (p = Ap[j]; p < Ap[j + 1]; p++)
                {
                    w[Ai[p]] = 1;
                    k       += (j == Ai[p]) ? 1 : 0; // count entries already on diagonal
                }
            }


            if (k == Math.Min(m, n)) // quick return if diagonal zero-free
            {
                for (i = 0; i < k; i++)
                {
                    jimatch[i] = i;
                }
                for (; i < m; i++)
                {
                    jimatch[i] = -1;
                }
                for (j = 0; j < k; j++)
                {
                    jimatch[m + j] = j;
                }
                for (; j < n; j++)
                {
                    jimatch[m + j] = -1;
                }

                return(jimatch);
            }

            for (i = 0; i < m; i++)
            {
                m2 += w[i];
            }

            // Transpose if needed
            SymbolicColumnStorage C = (m2 < n2) ? A.Transpose() : A.Clone();

            if (C == null)
            {
                return(jimatch);
            }

            n  = C.ColumnCount;
            m  = C.RowCount;
            Cp = C.ColumnPointers;

            int jmatch_offset = (m2 < n2) ? n : 0;
            int imatch_offset = (m2 < n2) ? 0 : m;

            w = new int[n]; // get workspace

            cheap = new int[n];
            js    = new int[n];
            iss   = new int[n];
            ps    = new int[n];

            for (j = 0; j < n; j++)
            {
                cheap[j] = Cp[j];                     // for cheap assignment
            }
            for (j = 0; j < n; j++)
            {
                w[j] = -1;                     // all columns unflagged
            }
            for (i = 0; i < m; i++)
            {
                jimatch[jmatch_offset + i] = -1; // nothing matched yet
            }
            q = Permutation.Create(n, seed);     // q = random permutation
            for (k = 0; k < n; k++)              // augment, starting at column q[k]
            {
                Augment(q[k], C.ColumnPointers, C.RowIndices, jimatch, jmatch_offset, cheap, w, js, iss, ps);
            }

            for (j = 0; j < n; j++)
            {
                jimatch[imatch_offset + j] = -1; // find row match
            }

            for (i = 0; i < m; i++)
            {
                if (jimatch[jmatch_offset + i] >= 0)
                {
                    jimatch[imatch_offset + jimatch[jmatch_offset + i]] = i;
                }
            }

            return(jimatch);
        }
Example #32
0
 /// <summary>
 /// Get the Hilbert position for a given point after balancing it, performing an optional permutation of the coordinates.
 /// The point may have its coordinates reduced in precision if bitsPerDimension is lower than the required value.
 /// </summary>
 /// <param name="unbalancedPoint">Point prior to balancing.</param>
 /// <param name="bitsPerDimension">Number of bits per dimension to use in forming the Hilbert position,
 /// which may be lower than the number of bits required to faithfully represent all coordinate values,
 /// causing the coordinate values of all coordinates to be reduced in precision.</param>
 /// <param name="perm">Permutation to apply to coordinates, scrambling their order in a consistent way for all points.</param>
 /// <returns>The Hilbert position.</returns>
 public BigInteger ToHilbertPosition(UnsignedPoint unbalancedPoint, int bitsPerDimension, Permutation <uint> perm = null)
 {
     uint[] balancedCoordinates;
     if (perm == null)
     {
         balancedCoordinates = Balance(unbalancedPoint.Coordinates, bitsPerDimension);
         return(balancedCoordinates.HilbertIndex(bitsPerDimension));
     }
     else
     {
         balancedCoordinates = Balance(unbalancedPoint.Coordinates, bitsPerDimension);
         var permutedCoordinates = perm.ApplyToArray(balancedCoordinates);
         return(permutedCoordinates.HilbertIndex(bitsPerDimension));
     }
 }
Example #33
0
 public ZhuEncoding(Permutation permutation, IVRPProblemInstance problemInstance)
     : base(permutation, problemInstance)
 {
 }
Example #34
0
 protected abstract double EvaluateMove(Permutation permutation, Func <int, int, double> distance, ItemList <BoolArray> realizations);
Example #35
0
 public static double Evaluate(Permutation tour, DistanceMatrix distanceMatrix, DoubleArray probabilities)
 {
     return(Evaluate(tour, (a, b) => distanceMatrix[a, b], probabilities));
 }
 protected abstract double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates);
 protected override double EvaluateMove(Permutation tour, Func <int, int, double> distance, ItemList <BoolArray> realizations)
 {
     return(EvaluateMove(tour, TranslocationMoveParameter.ActualValue, distance, realizations));
 }
Example #38
0
        /// <summary>
        /// Ordering and symbolic analysis for a LDL' factorization.
        /// </summary>
        /// <param name="order">Column ordering.</param>
        /// <param name="A">Matrix to factorize.</param>
        private void SymbolicAnalysis(ColumnOrdering order, CompressedColumnStorage <double> A)
        {
            int n = A.ColumnCount;

            var sym = this.S = new SymbolicFactorization();

            var ap = A.ColumnPointers;
            var ai = A.RowIndices;

            // P = amd(A+A') or natural
            var P    = AMD.Generate(A, order);
            var Pinv = Permutation.Invert(P);

            // Output: column pointers and elimination tree.
            var lp     = new int[n + 1];
            var parent = new int[n];

            // Workspace
            var lnz  = new int[n];
            var flag = new int[n];

            int i, k, p, kk, p2;

            for (k = 0; k < n; k++)
            {
                // L(k,:) pattern: all nodes reachable in etree from nz in A(0:k-1,k)
                parent[k] = -1;                         // parent of k is not yet known
                flag[k]   = k;                          // mark node k as visited
                lnz[k]    = 0;                          // count of nonzeros in column k of L
                kk        = (P != null) ? (P[k]) : (k); // kth original, or permuted, column
                p2        = ap[kk + 1];
                for (p = ap[kk]; p < p2; p++)
                {
                    // A(i,k) is nonzero (original or permuted A)
                    i = (Pinv != null) ? (Pinv[ai[p]]) : (ai[p]);
                    if (i < k)
                    {
                        // follow path from i to root of etree, stop at flagged node
                        for (; flag[i] != k; i = parent[i])
                        {
                            // find parent of i if not yet determined
                            if (parent[i] == -1)
                            {
                                parent[i] = k;
                            }
                            lnz[i]++;    // L(k,i) is nonzero
                            flag[i] = k; // mark i as visited
                        }
                    }
                }
            }

            // construct Lp index array from Lnz column counts
            lp[0] = 0;
            for (k = 0; k < n; k++)
            {
                lp[k + 1] = lp[k] + lnz[k];
            }

            sym.parent = parent;
            sym.cp     = lp;
            sym.q      = P;
            sym.pinv   = Pinv;
        }
Example #39
0
 public bool CanDo(IGrid grid, Permutation playerOrder)
 {
     return(grid.GetSymbol(Position) == BasicChunk.NoOwner);
 }
 public void PermuteMatrixColumnsThrowsInvalidOperationException()
 {
     var matrixp = CreateMatrix(TestData2D["Singular3x3"]);
     var permutation = new Permutation(new[] { 2, 0, 1 });
     Assert.Throws<InvalidOperationException>(() => matrixp.PermuteColumns(permutation));
 }
Example #41
0
				/// <summary>
				/// Begin evaluation of a single permutation
				/// </summary>
				/// <param name="permutation"></param>
				public void BeginPermutation(Permutation permutation)
				{
					// Clear counts
					myTopLevelCount = 0;
					myNonTopLevelCount = 0;

					// Get the new permutation number
					uint permutationIdentifier = myPermutationIdentifier;
					if (permutationIdentifier == PermutationIdentifierAfterShiftMask)
					{
						permutationIdentifier = 1; // Initial predecided only state is 0, avoid using 0
					}
					else
					{
						++permutationIdentifier;
					}
					myPermutationIdentifier = permutationIdentifier;

					foreach (FactTypeMapping mapping in permutation.Mappings)
					{
						if (!mapping.IsFromPreferredIdentifier)
						{
							SetState(mapping.TowardsObjectType, ObjectTypeStates.PermutationHasNonPreferredIdentifierMappingTowards, permutationIdentifier);
						}
						if (mapping.MappingDepth == MappingDepth.Deep)
						{
							SetState(mapping.FromObjectType, ObjectTypeStates.PermutationHasDeepMappingAway, permutationIdentifier);
						}
					}
				}
Example #42
0
        public static double Apply(TSPCoordinatesPathEvaluator evaluator, DoubleMatrix coordinates, Permutation tour)
        {
            DoubleMatrix c      = coordinates;
            Permutation  p      = tour;
            double       length = 0;

            for (int i = 0; i < p.Length - 1; i++)
            {
                length += evaluator.CalculateDistance(c[p[i], 0], c[p[i], 1], c[p[i + 1], 0], c[p[i + 1], 1]);
            }
            length += evaluator.CalculateDistance(c[p[p.Length - 1], 0], c[p[p.Length - 1], 1], c[p[0], 0], c[p[0], 1]);
            return(length);
        }
    public void OrderCrossoverApplyTest() {
      TestRandom random = new TestRandom();
      Permutation parent1, parent2, expected, actual;
      // The following test is based on an example from Eiben, A.E. and Smith, J.E. 2003. Introduction to Evolutionary Computation. Natural Computing Series, Springer-Verlag Berlin Heidelberg, pp. 55-56
      random.Reset();
      random.IntNumbers = new int[] { 3, 6 };
      parent1 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 });
      Assert.IsTrue(parent1.Validate());
      parent2 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 8, 2, 6, 7, 1, 5, 4, 0, 3 });
      Assert.IsTrue(parent2.Validate());
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 2, 7, 1, 3, 4, 5, 6, 0, 8 });
      Assert.IsTrue(expected.Validate());
      actual = OrderCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));
      // The following test is based on an example from Larranaga, P. et al. 1999. Genetic Algorithms for the Travelling Salesman Problem: A Review of Representations and Operators. Artificial Intelligence Review, 13, pp. 129-170.
      random.Reset();
      random.IntNumbers = new int[] { 2, 4 };
      parent1 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 2, 3, 4, 5, 6, 7 });
      Assert.IsTrue(parent1.Validate());
      parent2 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 1, 3, 5, 7, 6, 4, 2, 0 });
      Assert.IsTrue(parent2.Validate());
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 7, 6, 2, 3, 4, 0, 1, 5 });
      actual = OrderCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));
      // The following test is based on an example from Talbi, E.G. 2009. Metaheuristics - From Design to Implementation. Wiley, p. 218.
      random.Reset();
      random.IntNumbers = new int[] { 2, 5 };
      parent1 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 });
      Assert.IsTrue(parent1.Validate());
      parent2 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 7, 3, 0, 4, 8, 2, 5, 1, 6 });
      Assert.IsTrue(parent2.Validate());
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 0, 8, 2, 3, 4, 5, 1, 6, 7 });
      Assert.IsTrue(expected.Validate());
      actual = OrderCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));
      // The following test is not based on published examples
      random.Reset();
      random.IntNumbers = new int[] { 0, 5 };
      parent1 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 2, 1, 4, 3, 7, 8, 6, 0, 5, 9 });
      Assert.IsTrue(parent1.Validate());
      parent2 = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 5, 3, 4, 0, 9, 8, 2, 7, 1, 6 });
      Assert.IsTrue(parent2.Validate());
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 2, 1, 4, 3, 7, 8, 6, 5, 0, 9 });
      Assert.IsTrue(expected.Validate());
      actual = OrderCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));
      // based on the previous with changed breakpoints
      random.Reset();
      random.IntNumbers = new int[] { 6, 9 };
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 3, 4, 8, 2, 7, 1, 6, 0, 5, 9 });
      Assert.IsTrue(expected.Validate());
      actual = OrderCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));
      // another one based on the previous with changed breakpoints
      random.Reset();
      random.IntNumbers = new int[] { 0, 9 };
      expected = new Permutation(PermutationTypes.RelativeUndirected, new int[] { 2, 1, 4, 3, 7, 8, 6, 0, 5, 9 });
      Assert.IsTrue(expected.Validate());
      actual = OrderCrossover.Apply(random, parent1, parent2);
      Assert.IsTrue(actual.Validate());
      Assert.IsTrue(Auxiliary.PermutationIsEqualByPosition(expected, actual));

      // perform a test when the two permutations are of unequal length
      random.Reset();
      bool exceptionFired = false;
      try {
        OrderCrossover.Apply(random, new Permutation(PermutationTypes.RelativeUndirected, 8), new Permutation(PermutationTypes.RelativeUndirected, 6));
      }
      catch (System.ArgumentException) {
        exceptionFired = true;
      }
      Assert.IsTrue(exceptionFired);
    }
Example #44
0
 /// <summary>
 /// Permute the columns of a matrix according to a permutation.
 /// </summary>
 /// <param name="p">The column permutation to apply to this matrix.</param>
 /// <exception cref="InvalidOperationException">Always thrown</exception>
 /// <remarks>Permutation in diagonal matrix are senseless, because of matrix nature</remarks>
 public override void PermuteColumns(Permutation p)
 {
     throw new InvalidOperationException("Permutations in diagonal matrix are not allowed");
 }
Example #45
0
        public virtual void CanPermuteMatrixColumns([Values("Singular3x3", "Square3x3", "Wide2x3")] string name)
        {
            var matrix = CreateMatrix(TestData2D[name]);
            var matrixp = CreateMatrix(TestData2D[name]);

            var permutation = new Permutation(new[] { 2, 0, 1 });
            matrixp.PermuteColumns(permutation);

            Assert.AreNotSame(matrix, matrixp);
            Assert.AreEqual(matrix.RowCount, matrixp.RowCount);
            Assert.AreEqual(matrix.ColumnCount, matrixp.ColumnCount);
            for (var i = 0; i < matrix.RowCount; i++)
            {
                for (var j = 0; j < matrix.ColumnCount; j++)
                {
                    Assert.AreEqual(matrix[i, j], matrixp[i, permutation[j]]);
                }
            }
        }
 protected override double EvaluateMove(Permutation tour, Func <int, int, double> distance, DoubleArray probabilities)
 {
     return(EvaluateMove(tour, TranslocationMoveParameter.ActualValue, distance, probabilities));
 }
Example #47
0
 protected override TwoPointFiveMove[] GenerateMoves(Permutation permutation)
 {
     return(Apply(permutation, RandomParameter.ActualValue, SampleSizeParameter.ActualValue.Value));
 }
 protected override TwoPointFiveMove[] GenerateMoves(Permutation permutation)
 {
     return(new[] { Apply(permutation, RandomParameter.ActualValue) });
 }
 public override Solution Decode(Permutation permutation, PackingShape binShape, IList <PackingItem> items, bool useStackingConstraints)
 {
     return(Apply(permutation, binShape, items, useStackingConstraints));
 }
Example #50
0
        public virtual void CanPermuteMatrixRows(string name)
        {
            var matrix = CreateMatrix(TestData2D[name]);
            var matrixp = CreateMatrix(TestData2D[name]);

            var permutation = new Permutation(new[] { 2, 0, 1 });
            matrixp.PermuteRows(permutation);

            Assert.AreNotSame(matrix, matrixp);
            Assert.AreEqual(matrix.RowCount, matrixp.RowCount);
            Assert.AreEqual(matrix.ColumnCount, matrixp.ColumnCount);
            for (var i = 0; i < matrix.RowCount; i++)
            {
                for (var j = 0; j < matrix.ColumnCount; j++)
                {
                    AssertHelpers.AreEqual(matrix[i, j], matrixp[permutation[i], j]);
                }
            }
        }
Example #51
0
 public void Test_Number(long number1, long number2)
 {
     Assert.True(Permutation.IsPermuted(number1, number2));
 }
        public static double EvaluateMove(Permutation tour, TranslocationMove move, Func <int, int, double> distance, ItemList <BoolArray> realizations)
        {
            var afterMove = (Permutation)tour.Clone();

            TranslocationManipulator.Apply(afterMove, move.Index1, move.Index1, move.Index3);
            double moveQuality = 0;
            var    edges       = new int[12];
            var    indices     = new int[12];

            edges[0]   = tour.GetCircular(move.Index1 - 1);
            indices[0] = DecreaseCircularIndex(tour.Length, move.Index1);
            edges[1]   = tour[move.Index1];
            indices[1] = move.Index1;
            edges[2]   = tour[move.Index1];
            indices[2] = move.Index1;
            edges[3]   = tour.GetCircular(move.Index1 + 1);
            indices[3] = IncreaseCircularIndex(tour.Length, move.Index1);

            edges[6]   = afterMove.GetCircular(move.Index3 - 1);
            indices[6] = DecreaseCircularIndex(afterMove.Length, move.Index3);
            edges[7]   = afterMove[move.Index3];
            indices[7] = move.Index3;
            edges[8]   = afterMove[move.Index3];
            indices[8] = move.Index3;
            edges[9]   = afterMove.GetCircular(move.Index3 + 1);
            indices[9] = IncreaseCircularIndex(afterMove.Length, move.Index3);

            if (move.Index3 > move.Index1)
            {
                edges[4]    = tour[move.Index3];
                indices[4]  = move.Index3;
                edges[5]    = tour.GetCircular(move.Index3 + 1);
                indices[5]  = indices[9];
                edges[10]   = afterMove.GetCircular(move.Index1 - 1);
                indices[10] = indices[0];
                edges[11]   = afterMove[move.Index1];
                indices[11] = move.Index1;
            }
            else
            {
                edges[4]    = tour.GetCircular(move.Index3 - 1);
                indices[4]  = indices[6];
                edges[5]    = tour[move.Index3];
                indices[5]  = move.Index3;
                edges[10]   = afterMove[move.Index1];
                indices[10] = move.Index1;
                edges[11]   = afterMove.GetCircular(move.Index1 + 1);
                indices[11] = indices[3];
            }
            int[] aPosteriori = new int[12];
            foreach (var realization in realizations)
            {
                for (int i = 0; i < edges.Length; i++)
                {
                    Permutation tempPermutation;
                    if (i < 6)
                    {
                        tempPermutation = tour;
                    }
                    else
                    {
                        tempPermutation = afterMove;
                    }
                    if (realization[edges[i]])
                    {
                        aPosteriori[i] = edges[i];
                    }
                    else
                    {
                        int j = 1;
                        if (i % 2 == 0)
                        {
                            // find nearest predecessor in realization if source edge
                            while (!realization[tempPermutation.GetCircular(indices[i] - j)])
                            {
                                j++;
                            }
                            aPosteriori[i] = tempPermutation.GetCircular(indices[i] - j);
                        }
                        else
                        {
                            // find nearest successor in realization if target edge
                            while (!realization[tempPermutation.GetCircular(indices[i] + j)])
                            {
                                j++;
                            }
                            aPosteriori[i] = tempPermutation.GetCircular(indices[i] + j);
                        }
                    }
                }
                if (!(aPosteriori[0] == aPosteriori[2] && aPosteriori[1] == aPosteriori[3]) &&
                    !(aPosteriori[0] == aPosteriori[4] && aPosteriori[1] == aPosteriori[5]) &&
                    !(aPosteriori[2] == aPosteriori[4] && aPosteriori[3] == aPosteriori[5]))
                {
                    // compute cost difference between the two a posteriori solutions
                    moveQuality = moveQuality + distance(aPosteriori[6], aPosteriori[7]) + distance(aPosteriori[8], aPosteriori[9]) + distance(aPosteriori[10], aPosteriori[11]);
                    moveQuality = moveQuality - distance(aPosteriori[0], aPosteriori[1]) - distance(aPosteriori[2], aPosteriori[3]) - distance(aPosteriori[4], aPosteriori[5]);
                }
                Array.Clear(aPosteriori, 0, aPosteriori.Length);
            }
            // return average of cost differences
            return(moveQuality / realizations.Count);
        }
        static void Main(string[] args)
        {
            string[] strings =
            {
                "(){}",
                ")"
            };

            foreach (var s in strings)
            {
                string results = BracketDelimiter.IsBalanced(s) ? "succes" : "niet oké";
                Debug.WriteLine(results);
            }

            var resultTot = PostfixCalculator.Calculate("12 10-2+25*10/");

            Console.WriteLine(resultTot);

            //BracketDelimiter.IsBalanced("(){}");

            //BracketDelimiter.IsBalanced("()");
            //BracketDelimiter.IsBalanced("((");

            //BracketDelimiter.IsBalanced("{()}");
            //BracketDelimiter.IsBalanced("{()");
            //BracketDelimiter.IsBalanced("''");

            ////var resultS =  BracketDelimiter.IsBalanced("<?<??>?>");
            //var resultSS = BracketDelimiter.IsBalanced("for(int i = 0; i< 100; i++){}");

            //Console.WriteLine(resultSS);
            Console.ReadLine();
            return;


            OddNumberPrinter.ExecuteEven(2);
            OddNumberPrinter.ExecuteOdd(3);



            var result = InterestCalculator.Calculate(2, 1, 5000);

            List <string> items = new List <string> {
                "a", "b", "c", "d", "e", "f", "g"
            };

            Permutation.Permutations(items);
            Console.WriteLine(Permutation.GetPermutationCount);

            //Printer.PrintAsc();
            //Console.WriteLine(NaturalCounter.Execute(5));
            //DigitSeperator.Execute(255);
            //Console.WriteLine(DigitCounter.Execute(12345));
            //OddNumberPrinter.Execute(20);
            ItterativeIndex ittIdIndex = new ItterativeIndex();

            int value = ittIdIndex.IndexOf(new int[] { 1, 2, 3, 4, 5 }, 5, 0);


            IsPrime.Execute(37, 37 / 2);
            IsPalindrome.Execute("ABBA");
            Console.WriteLine(
                FactorialCalculator.Execute(8));
            //ForLoopProblem.Problem();

            char startPeg   = 'A';  // start tower in output
            char endPeg     = 'C';  // end tower in output
            char tempPeg    = 'B';  // temporary tower in output
            int  totalDisks = 1200; // number of disks

            //TowersOfHanoi.Solve(totalDisks, startPeg, endPeg, tempPeg);


            int[,] random = new int[, ]
            {
                { 200, 400 },
                { 2000, 4176 },
                { 20000, 40000 },
                { 50000, 50000 }
            };

            //var c = _2DArraySum.GetHighestSum(random);

            var getHighestSummedArray = new _2DArraySumAsClass <int[, ]>();

            Console.WriteLine("Highest value" + getHighestSummedArray.GetHighestSum(random));


            //Create linked list
            LinkedListExercise linkedListExercise = new LinkedListExercise();

            //Add data
            linkedListExercise.Employees.AddLast(new Employee("Bob", 5));
            linkedListExercise.Employees.AddLast(new Employee("Alice", 5000));

            //ShallowCopy with IClonable
            var shallowCopy = linkedListExercise.ShallowCopy();
            //Shallow copy with Collection<T>() ctor
            var shallowCopyCollection = linkedListExercise.ShallowCopyCollection();
            //Deep copy
            var deepCopy = linkedListExercise.DeepCopy();


            //var bucketSort = new BucketSort();
            //bucketSort.Execute(new[] { 8, 2, 122, 1, 99, 3, 4, 2 });

            //BubbleSort bubbleSort = new BubbleSort();
            //var res = bubbleSort.Execute(new int[]{8,2, 122, 1});

            //var x = new Solution3();
            //x.Slow(100);
            //x.Fast(100);

            //var binarySearch = new BinarySearch();
            //var array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
            //int pos = binarySearch.Execute(array, 10);

            //var input = "8,1,6;3,5,7;4,9,2";
            //var array = (from x in input.Split(',', ';') select int.Parse(x)).ToArray();
            //var magic = new MagicSquare();
            //magic.Execute(3);

            //magic.ExecuteCorrect(3);
            //MagicSquare.RunMagicSquare(3);


            //Binary Search recurisve.
            //int[] testArray = { 1,2,3,4,5,6,7,8,9,10,11,12};
            //var length = testArray.Length;
            //var searchFor = 10;

            //Console.WriteLine(BinarySearch.RecursiveV2(searchFor, testArray, 0, length));
            //Console.WriteLine($"Self made {BinarySearch.BinarySearchRecursiveSelf(testArray, 0, length, searchFor)}");


            //Console.WriteLine(
            //    ADS.Core.Lesson_2.Converter.DecimalToBin(10));

            //Console.WriteLine("Bin 2 dec " + ADS.Core.Lesson_2.Converter.Bin2dec(1100));
            //Console.WriteLine(ADS.Core.Lesson_2.Converter.BinToDecimal("10101"));


            //Console.WriteLine(Palindrome.IsPalindrome("racecar"));

            // Console.WriteLine(ReverseString.ExecuteV1("ban"));
            // Console.WriteLine(ReverseString.Execute("ban"));

            // ArrayCombiner arrayCombiner = new ArrayCombiner();
            //var x = arrayCombiner.Execute(new int[] { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 },
            //     new int[] { 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 });

            //ArrayListCombiner arrayListCombiner = new ArrayListCombiner();

            // var y = arrayListCombiner.Merge(new List<int> { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 },
            //    new List<int> { 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 });


            // Create first polynomial
            var polynomial1 = new Polynomial();

            polynomial1.Add(new Term(1, 2));
            polynomial1.Add(new Term(2, 2));
            polynomial1.Add(new Term(3, 0));


            // Create second polynomial
            var polynomial2 = new Polynomial();

            polynomial2.Add(new Term(-1, 3));
            polynomial2.Add(new Term(1, 1));
            polynomial2.Add(new Term(1, 2));

            Stopwatch x = new Stopwatch();

            x.Start();
            Polynomial polyX        = polynomial1.SumWorking(polynomial2);
            var        termsWorking = polyX.GetAllTerms();

            x.Stop();
            Console.WriteLine(x.ElapsedTicks + "TICKS");
            x.Reset();

            x.Start();

            Polynomial polyOptimized = polynomial1.OptimizedAlgorithm(polynomial2);
            var        optimzedTerms = polyX.GetAllTerms();

            x.Stop();
            Console.WriteLine(x.ElapsedTicks + "TICKS");
            x.Reset();

            // Determine the sum
            Polynomial polynomialSum = polynomial1.Sum(polynomial2);
            var        terms         = polynomialSum.GetAllTerms();

            for (int i = 0; i < polynomialSum.GetAllTerms().Count; i++)
            {
                Console.Write($"{terms[i].toString()}\t");
            }

            //TowersOfHanoi.Solve(64);
            //TowersOfHanoi.TowerHanoi(3);
            //-> coeff = 1 - X^ > ex3
            //2X^3
            //-5^0

            //var c = BinarySearch.binarySearchFloris(new int[] { 1,2,3,4,5,6,7,8,9,10 }, 2);

            Hangman hangman = new Hangman();

            hangman.ChooseWord();

            bool val = true;

            while (val)
            {
                string input = Console.ReadLine();
                hangman.GuessWord(input);

                if (input == "exit")
                {
                    val = false;
                }
            }

            int[] arr1 = new int[] { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
            int[] arr2 = new int[] { 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 };

            int[] execute = ArrayCombiner.combineArray(arr2, arr1);

            //var intList = new ArrayList();
            //intList[1] as int? = 2;

            var res12 = ArrayListCombiner.Merge(new ArrayList()
            {
                1, 2, 3, 4
            }, new ArrayList()
            {
                1, 2, 3, 4
            });

            int max = MaxRec.Execute(new int[] { 1, 2, 3, 4, 1204 });


            Console.WriteLine();

            //Console.WriteLine(Converter.BinToDecimal("1011"));
            Console.ReadLine();
        }
Example #54
0
        private void GenerateImage()
        {
            if ((pictureBox.Width > 0) && (pictureBox.Height > 0))
            {
                if (Content == null)
                {
                    pictureBox.Image = null;
                }
                else
                {
                    DoubleMatrix coordinates   = Content.Coordinates;
                    Permutation  permutation   = Content.Permutation;
                    DoubleArray  probabilities = Content.Probabilities;
                    Bitmap       bitmap        = new Bitmap(pictureBox.Width, pictureBox.Height);

                    if ((coordinates != null) && (coordinates.Rows > 0) && (coordinates.Columns == 2) && (probabilities.Length == coordinates.Rows))
                    {
                        double xMin = double.MaxValue, yMin = double.MaxValue, xMax = double.MinValue, yMax = double.MinValue;
                        for (int i = 0; i < coordinates.Rows; i++)
                        {
                            if (xMin > coordinates[i, 0])
                            {
                                xMin = coordinates[i, 0];
                            }
                            if (yMin > coordinates[i, 1])
                            {
                                yMin = coordinates[i, 1];
                            }
                            if (xMax < coordinates[i, 0])
                            {
                                xMax = coordinates[i, 0];
                            }
                            if (yMax < coordinates[i, 1])
                            {
                                yMax = coordinates[i, 1];
                            }
                        }

                        int    border = 20;
                        double xStep  = xMax != xMin ? (pictureBox.Width - 2 * border) / (xMax - xMin) : 1;
                        double yStep  = yMax != yMin ? (pictureBox.Height - 2 * border) / (yMax - yMin) : 1;

                        Point[] points = new Point[coordinates.Rows];
                        for (int i = 0; i < coordinates.Rows; i++)
                        {
                            points[i] = new Point(border + ((int)((coordinates[i, 0] - xMin) * xStep)),
                                                  bitmap.Height - (border + ((int)((coordinates[i, 1] - yMin) * yStep))));
                        }

                        using (Graphics graphics = Graphics.FromImage(bitmap)) {
                            if (permutation != null && permutation.Length > 1)
                            {
                                Point[] tour = new Point[permutation.Length];
                                for (int i = 0; i < permutation.Length; i++)
                                {
                                    if (permutation[i] >= 0 && permutation[i] < points.Length)
                                    {
                                        tour[i] = points[permutation[i]];
                                    }
                                }
                                graphics.DrawPolygon(Pens.Black, tour);
                            }
                            for (int i = 0; i < points.Length; i++)
                            {
                                graphics.FillRectangle(Brushes.Red, points[i].X - 2, points[i].Y - 2, Convert.ToInt32(probabilities[i] * 20), Convert.ToInt32(probabilities[i] * 20));
                            }
                        }
                    }
                    else
                    {
                        using (Graphics graphics = Graphics.FromImage(bitmap)) {
                            graphics.Clear(Color.White);
                            Font   font    = new Font(FontFamily.GenericSansSerif, 12, FontStyle.Regular);
                            string text    = "No coordinates defined or in wrong format.";
                            SizeF  strSize = graphics.MeasureString(text, font);
                            graphics.DrawString(text, font, Brushes.Black, (float)(pictureBox.Width - strSize.Width) / 2.0f, (float)(pictureBox.Height - strSize.Height) / 2.0f);
                        }
                    }
                    pictureBox.Image = bitmap;
                }
            }
        }
Example #55
0
 public void Undo(IGrid grid, Permutation playerOrder)
 {
     grid.SetSymbol(Position, BasicChunk.NoOwner, true);
 }
Example #56
0
 public void Do(IGrid grid, Permutation playerOrder)
 {
     grid.SetSymbol(Position, Owner, true);
 }
Example #57
0
 protected override double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates)
 {
     return(EvaluateByCoordinates(permutation, TranslocationMoveParameter.ActualValue, coordinates, this));
 }
Example #58
0
        public void GivenOnePermutationsWhenCheckingForEqualityWithNonPermutationObjectThenTheyAreDifferent()
        {
            Permutation permutation1 = new Permutation(12, 34);

            Assert.IsFalse(permutation1.Equals(this));
        }
Example #59
0
 /// <summary>
 /// Permute the rows of a matrix according to a permutation.
 /// </summary>
 /// <param name="p">The row permutation to apply to this matrix.</param>
 /// <exception cref="InvalidOperationException">Always thrown</exception>
 /// <remarks>Permutation in diagonal matrix are senseless, because of matrix nature</remarks>
 public override void PermuteRows(Permutation p)
 {
     throw new InvalidOperationException("Permutations in diagonal matrix are not allowed");
 }
Example #60
0
 protected override double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix)
 {
     return(EvaluateByDistanceMatrix(permutation, TranslocationMoveParameter.ActualValue, distanceMatrix));
 }