Пример #1
0
 public void MergeWithBest(Solution best,Random random)
 {
     Difference diff = new Difference(this, best);
     if (diff.Distance != 0)
     {
         int position = random.Next(diff.Distance);
         position = diff.Positions[position];
         City newBest = best.Cities[position];
         //we do have new city, so there's need for correction
         //find current instance
         City curSelected = Cities[position];
         Cities[Cities.IndexOf(newBest)] = curSelected;
         Cities[position] = newBest;
     }
 }
Пример #2
0
        public Difference(Solution from, Solution to)
        {
            var i1 = from.Cities.GetEnumerator();
            var i2 = to.Cities.GetEnumerator();
            Positions = new List<int>();

            for(int i = 0; i < from.Cities.Count; ++i)
            {
                i1.MoveNext();
                i2.MoveNext();

                if (i1.Current != i2.Current)
                {
                    Positions.Add(i);
                }
            }
        }
Пример #3
0
 private void Shuffle(Solution s)
 {
     int n = s.Cities.Count;
     while (n > 1)
     {
         --n;
         int k = randomizer.Next(n + 1);
         s.SwapCities(k, n);
     }
 }
Пример #4
0
        private void LocalSearch(Solution s, State state)
        {
            int m, n;
            double baseEvaluation = s.Evaluate(state.Warehouse, state.K);

            for (int i = 0; i < LSTrials; ++i)
            {
                m = randomizer.Next(s.Cities.Count);
                do{
                    n = randomizer.Next(s.Cities.Count);
                }while(m == n);
                s.SwapCities(m, n);
                if (s.Evaluate(state.Warehouse, state.K) < baseEvaluation)
                {
                    //better permutation
                    baseEvaluation = s.Evaluation;
                }
                else
                {
                    //worse permutation, we go back to previous one
                    s.SwapCities(m, n);
                    s.Evaluate(state.Warehouse, state.K);
                }
            }
        }
Пример #5
0
        private IList<Solution> Initialize(State s)
        {
            IList<Solution> solutions = new List<Solution>();
            Solution solution;

            solutions.Add(GenerateGreedySolution(s));
            Console.WriteLine(solutions[0].Evaluate(s.Warehouse, s.K));

            for (int i = 1; i < s.PopulationSize; ++i)
            {
                solution = new Solution(new List<City>(s.Cities));
                Shuffle(solution);
                solutions.Add(solution);
            }

            return solutions;
        }