Beispiel #1
0
        //[TestCase("tsp3.txt", 14.00)]
        public void ComputeTest(string fileName, double expected)
        {
            var lines = File.ReadAllLines(fileName);
            var n     = int.Parse(lines[0]);
            var list  = new List <(double x, double y)>();

            foreach (var ln in lines.Skip(1).Select(l => l.Split(" ")))
            {
                var x = double.Parse(ln[0]);
                var y = double.Parse(ln[1]);
                list.Add((x, y));
            }

            var clique = new double[n + 1, n + 1];

            for (int i = 0; i < n; i++)
            {
                for (int j = i + 1; j < n; j++)
                {
                    var a    = list[i];
                    var b    = list[j];
                    var dist = TravelingSalesman.EuclideanDistance(a.x, a.y, b.x, b.y);;
                    clique[i + 1, j + 1] = dist;
                    clique[j + 1, i + 1] = dist;
                }
            }

            _algo = new TravelingSalesman(clique, n);
            var result = _algo.Compute();

            Assert.That(Math.Round(result, 2), Is.EqualTo(expected));
        }
        public double Compute(City[] cities)
        {
            var n         = cities.Count();
            var unvisited = new HashSet <int>();
            var result    = 0d;

            for (int i = 1; i < n; i++)
            {
                unvisited.Add(i);
            }

            var last = 0;

            while (unvisited.Count > 0)
            {
                var minDist = double.MaxValue;
                var minId   = n;

                foreach (var curId in unvisited)
                {
                    var curDist = TravelingSalesman.EuclideanDistance(cities[last].x, cities[last].y, cities[curId].x, cities[curId].y);

                    if (curDist < minDist || (curDist == minDist && curId < minId))
                    {
                        minId   = curId;
                        minDist = curDist;
                    }
                }

                unvisited.Remove(minId);

                last    = minId;
                result += minDist;
            }

            return(result + TravelingSalesman.EuclideanDistance(cities[0].x, cities[0].y, cities[last].x, cities[last].y));
        }