dimanche 5 novembre 2017

C# Need to instantiate several objects of same class with different random numbers [duplicate]

This question already has an answer here:

So the goal of this code is to calculate distances between random points on a "map", listed here as "cities". The logic works except that I can't get each instantiation of my Point class to generate random numbers so that each "city" is unique (or at least has a good chance of being unique, I'm ok with some repeated ints). I know similar questions have been asked but I have been banging my head against a wall trying to understand them and am coming up flat. My Point class and it's constructor are where my code is failing.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace SoloLearn
{
    class Point
    {
        int x;
        int y;
        string name;

        public Point(string name)
        {
            Random rng1 = new Random();
            this.x = rng1.Next(100);

            Random rng2 = new Random();
            this.y = rng2.Next(100);

            this.name = name;
        }

        public static double Distance(Point a, Point b)
        {
            return Math.Pow((a.x - b.x), 2) + Math.Pow((a.y - b.y), 2);

        }

        static void Main(string[] args)
        {
            Point a = new Point("Lisbon");
            Point b = new Point("Chicago");
            Point c = new Point("Cleveland");
            Point d = new Point("Tokyo");
            Point e = new Point("Philadelphia");


            Distance(a, b);

            List <Point> PointList = new List <Point>();
            PointList.Add(a);
            PointList.Add(b);
            PointList.Add(c);
            PointList.Add(d);
            PointList.Add(e);

            int size = PointList.Count;
            double shortest = Distance(a, b);
            string city1 = PointList[0].name;
            string city2 = PointList[1].name;

            for (int i = 0; i < size; i++)
            {
                Console.WriteLine(PointList[i].name + " " + PointList[i].x + " " + PointList[i].y);
            }

            for (int i = 0; i < size; i++)
            {
                Point key = PointList[i];

                for (int j = i + 1; j < size; j++)
                {
                    Point compare = PointList[j];

                    if (Distance(key, compare) < shortest)
                    {
                        shortest = Distance(key, compare);
                        city1 = key.name;
                        city2 = compare.name;
                    }
                }
            }
            Console.WriteLine("{0} and {1} are the closest cities at {2} miles apart", city1, city2, shortest);

        }
    }
}




Aucun commentaire:

Enregistrer un commentaire