示例#1
0
        public WorldMapAnneal()
        {
            InitializeComponent();
            Random rand = new Random();
            // place the cities at random locations
            int height = this.Height - 50;
            int width = this.Width - 10;
            this.cities = new City[WorldMapAnneal.CITY_COUNT];
            for (int i = 0; i < WorldMapAnneal.CITY_COUNT; i++)
            {
                this.cities[i] = new City((int)(rand.NextDouble() * width),
                        (int)(rand.NextDouble() * height));
            }

            this.anneal = new TSPSimulatedAnnealing(this.cities, START_TEMPERATURE,
                    STOP_TEMPERATURE, CYCLES);

            bool[] taken = new bool[this.cities.Length];
            int[] path = new int[this.cities.Length];

            for (int i = 0; i < path.Length; i++)
            {
                taken[i] = false;
            }
            for (int i = 0; i < path.Length - 1; i++)
            {
                int icandidate;
                do
                {
                    icandidate = (int)(rand.NextDouble() * path.Length);
                } while (taken[icandidate]);
                path[i] = icandidate;
                taken[icandidate] = true;
                if (i == path.Length - 2)
                {
                    icandidate = 0;
                    while (taken[icandidate])
                    {
                        icandidate++;
                    }
                    path[i + 1] = icandidate;
                }
            }

            this.anneal.PutArray(path);

            start();
        }
示例#2
0
        /// <summary>
        /// Setup and solve the TSP.
        /// </summary>
        public void Solve()
        {
            StringBuilder builder = new StringBuilder();

            InitCities();

            anneal = new TSPSimulatedAnnealing(cities, START_TEMP, STOP_TEMP,
                    CYCLES);

            InitPath();

            int sameSolutionCount = 0;
            int iteration = 1;
            double lastSolution = Double.MaxValue;

            while (sameSolutionCount < MAX_SAME_SOLUTION)
            {
                anneal.Iteration();

                double thisSolution = anneal.Score;

                builder.Length = 0;
                builder.Append("Iteration: ");
                builder.Append(iteration++);
                builder.Append(", Best Path Length = ");
                builder.Append(thisSolution);

                app.WriteLine(builder.ToString());

                if (Math.Abs(lastSolution - thisSolution) < 1.0)
                {
                    sameSolutionCount++;
                }
                else
                {
                    sameSolutionCount = 0;
                }

                lastSolution = thisSolution;
            }

            app.WriteLine("Good solution found:");
            DisplaySolution();

        }