Exemple #1
0
        static void Main(string[] args)
        {
            var pathToData = "./Data/input.txt";

            if (args.Length == 1)
            {
                pathToData = args[0];
            }
            var points = PointCreator.ReadPointsFromFile(pathToData).ToList();

            for (var i = 0; i < points.Count; i++)
            {
                Console.WriteLine($"{i}-{points[i].X};{points[i].Y}");
            }

            var GS  = new GrahamScan(points);
            var res = GS.GetSortPoints().ToList();

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Result:");
            for (var i = 0; i < res.Count; i++)
            {
                Console.WriteLine($"{i}-{res[i].X};{res[i].Y}");
            }
            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
Exemple #2
0
    public void CalculateConvexHull()
    {
        // Destroy the previous game objects.
        if (points != null)
        {
            Destroy(points);
        }

        // Generate random points.
        input = VectorUtils.RandomVectorList(numberOfPoints);

        // Create the game object representation of the points.
        points = new GameObject {
            name = "Points"
        };

        foreach (Vector2 v in input)
        {
            GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            sphere.transform.parent     = points.transform;
            sphere.transform.position   = new Vector3(v.x, v.y, 0);
            sphere.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
        }

        System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
        watch.Start();

        // Calculate the convex hull.
        IConvexHull convexHull = new GrahamScan();

        output = convexHull.Compute(input);

        watch.Start();
        Debug.Log("ConvexHull elapsed time: " + watch.ElapsedMilliseconds);
    }
Exemple #3
0
        public void GetSortPointTest()
        {
            var points = new List <Point>()
            {
                new Point(100, 100),
                new Point(400, 100),
                new Point(100, 400),
                new Point(400, 400),
                new Point(200, 200)
            };
            var res   = new GrahamScan(points).GetSortPoints().ToList();
            var lines = new List <Line>();

            for (int i = 0; i < res.Count - 1; i++)
            {
                lines.Add(new Line
                {
                    Start = res[i],
                    End   = res[i + 1]
                });
            }

            for (int i = 0; i < lines.Count - 1; i++)
            {
                var firstLine = lines[i];
                var isNext    = IsNext(firstLine, lines[i + 1]);
                Assert.IsTrue(isNext);
                for (var j = i + 2; j < lines.Count; j++)
                {
                    var notCrossing = IsNotCross(firstLine, lines[j]);
                    //Assert.IsTrue(notCrossing);
                }
            }
        }
Exemple #4
0
        public void GrahamScan_LinePoints_ShouldNotThrowEmptyStackException()
        {
            //Arrange
            var data = new Point[] { new Point(1, 1), new Point(2, 2), new Point(3, 3), new Point(4, 4) };

            //Act
            var result = GrahamScan.Process(data);

            //Assert
            Assert.IsTrue(true);
        }
Exemple #5
0
 /**
   * Unit tests the {@code GrahamScan} data type.
   * Reads in an integer {@code n} and {@code n} points (specified by
   * their <em>x</em>- and <em>y</em>-coordinates) from standard input;
   * computes their convex hull; and prints out the points on the
   * convex hull to standard output.
   *
   * @param args the command-line arguments
   */
  public static void main(String[] args) {
      int n = StdIn.readInt();
      Point2D[] points = new Point2D[n];
      for (int i = 0; i < n; i++) {
          int x = StdIn.readInt();
          int y = StdIn.readInt();
          points[i] = new Point2D(x, y);
      }
      GrahamScan graham = new GrahamScan(points);
      for (Point2D p : graham.hull())
          StdOut.println(p);
  }
Exemple #6
0
        static void GrahamScanDemo()
        {
            GrahamScan gs = new GrahamScan();

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            gs.convexHull(listPoints);
            stopwatch.Stop();
            float elapsed_time = stopwatch.ElapsedMilliseconds;
            Console.WriteLine("Elapsed time: {0} milliseconds", elapsed_time);
            Console.WriteLine("Press enter to close...");
            Console.ReadLine();
        }
Exemple #7
0
    // Start is called before the first frame update
    void Start()
    {
        var objects = GameObject.FindGameObjectsWithTag("User0");

        foreach (var e in objects)
        {
            m_points.Add(e.transform.position);
        }

        int result = GrahamScan.Run(m_points);

        for (int i = 0; i < result; ++i)
        {
            GameObject obj = GameObject.Instantiate(m_instantiate);
            obj.transform.position = m_points[i];
        }
    }
    /// <summary>
    /// [CalucrateTerritory]
    /// Playerのテリトリーを計算する, 基本使わないこと
    /// 引数1: Player infomation
    /// </summary>
    public void CalucrateTerritory(PlayerInfo playerInfo)
    {
        //リストクリア
        playerInfo.allTerritoryPoints.Clear();
        playerInfo.borderTerritorys.Clear();
        playerInfo.borderTerritoryPoints.Clear();
        playerInfo.territorialArea.Clear();
        m_grahamResult.Clear();
        //ポジション記録, ソート用リスト構築
        for (int i = 0, count = playerInfo.allTerritorys.Count; i < count; ++i)
        {
            playerInfo.allTerritoryPoints.Add(playerInfo.allTerritorys[i].transform.position);
            m_grahamResult.Add(new GrahamScan.CustomFormat(playerInfo.allTerritoryPoints[i], i));
        }

        //グラハムソート
        int result = GrahamScan.Run(m_grahamResult);

        if (result < m_grahamResult.Count - 1)
        {
            m_grahamResult.RemoveRange(result, m_grahamResult.Count - result);
        }

        //結果を各リストに構築
        for (int i = 0; i < result; ++i)
        {
            playerInfo.borderTerritorys.Add(playerInfo.allTerritorys[m_grahamResult[i].userID]);
            playerInfo.borderTerritoryPoints.Add(playerInfo.allTerritoryPoints[m_grahamResult[i].userID]);
        }

        //ボリューム追加した状態でグラハムソート
        for (int i = 0, count = m_grahamResult.Count; i < count; ++i)
        {
            for (int k = 0, length = m_volumePoints.Length; k < length; ++k)
            {
                m_grahamResult.Add(new GrahamScan.CustomFormat(m_grahamResult[i].position + (m_volumePoints[k] * m_radiusVolume), -1));
            }
        }
        result = GrahamScan.Run(m_grahamResult);

        //結果をリストに構築
        for (int i = 0; i < result; ++i)
        {
            playerInfo.territorialArea.Add(m_grahamResult[i].position);
        }
    }
Exemple #9
0
    private void Start()
    {
        mode = Mode.Create;

        point = Resources.Load <GameObject>("Prefabs/Point");

        camera     = Camera.main;
        hullLine   = GameObject.Find("Hull Line").GetComponent <LineRenderer>();
        graphLines = GameObject.Find("Graph Lines").transform;
        pathLine   = GameObject.Find("Path Line").GetComponent <LineRenderer>();

        hull       = new Transform[0];
        path       = new Edge[0];
        graph      = new Graph();
        grahamScan = new GrahamScan();
        voronoi    = new Voronoi(0f);
        pathfinder = new Pathfinder();
    }
Exemple #10
0
        public void TestQuad()
        {
            List <Vector3> points = new List <Vector3>();

            points.Add(new Vector3(1, 3, 0));
            points.Add(new Vector3(-1, 3, 0));
            points.Add(new Vector3(1, 1, 0));
            points.Add(new Vector3(-1, 1, 0));
            points.Add(new Vector3(2, 4, 0));
            points.Add(new Vector3(-2, 4, 0));
            points.Add(new Vector3(2, 0, 0));
            points.Add(new Vector3(-2, 0, 0));

            GrahamScan scan = new GrahamScan(points);

            Console.WriteLine(scan.EdgePoints.Count + " points.");

            scan.EdgePoints.ForEach(it => Console.WriteLine(it));
        }
        private void button3_Click(object sender, EventArgs e)
        {
            GrahamScan   ch = new GrahamScan();
            IPositionSet ps = ch.ConvexHull(getPoints2((Bitmap)pictureBox1.Image));
            Graphics     g  = Graphics.FromImage(pictureBox1.Image);
            IPosition    p1 = ps.GetPosition();
            IPosition    p2 = ps.GetPosition();

            while (p2 != null)
            {
                g.DrawLine(new Pen(Color.Green), new PointF(p1.GetX(), p1.GetY()), new PointF(p2.GetX(), p2.GetY()));
                p1 = p2;
                p2 = ps.GetPosition();
            }
            ps.InitToTraverseSet();
            p2 = ps.GetPosition();
            g.DrawLine(new Pen(Color.Green), new PointF(p1.GetX(), p1.GetY()), new PointF(p2.GetX(), p2.GetY()));

            pictureBox1.Refresh();
        }
Exemple #12
0
    public void CalculateTerritory()
    {
        territoryPoints.Clear();

        {
            int i = 0;
            foreach (var e in markPoints)
            {
                territoryPoints.Add(e.Value.gameObject.transform.position);
                ++i;
            }
        }

        int result = GrahamScan.Run(territoryPoints);

        if (result < territoryPoints.Count - 1)
        {
            territoryPoints.RemoveRange(result, territoryPoints.Count - result);
        }

        TerritoryManager.instance.AddVolumePoints(territoryPoints);
        result = GrahamScan.Run(territoryPoints);
        if (result < territoryPoints.Count - 1)
        {
            territoryPoints.RemoveRange(result, territoryPoints.Count - result);
        }

        Debug.Log(markPoints.Count + "+" + territoryPoints.Count);

        if (m_lineRenderer != null)
        {
            m_lineRenderer.positionCount = territoryPoints.Count;
            for (int i = 0; i < territoryPoints.Count; ++i)
            {
                m_lineRenderer.SetPosition(i, territoryPoints[i]);
            }
        }
    }
        void GSCH(double n, Object o)
        {
            GrahamScan GS = new GrahamScan();

            GS.ConvexHull((IPositionSet)o);
        }
Exemple #14
0
        private void button1_Click(object sender, EventArgs e)
        {
            IConvexHullEngine convexhull;
            int n;

            switch (comboBox1.SelectedIndex)
            {
            case 0:
                convexhull = new GrahamScan();
                break;

            case 1:
                //convexhull = new QuickHull();
                convexhull = new M2M_CH();
                break;

            default:
                return;
            }
            try
            {
                n = Int32.Parse(textBox1.Text);
            }
            catch (Exception)
            {
                return;
            }

            //Point[] ps = new Point[n];
            PositionSetEdit_ImplementByICollectionTemplate ps = new PositionSetEdit_ImplementByICollectionTemplate();
            Random r = new Random(DateTime.Now.Millisecond);

            //if (true)
            {
                int minx = (int)(pb.Width * 0.05);
                int miny = (int)(pb.Height * 0.05);
                for (int i = 0; i < n; i++)
                {
                    int x = r.Next(minx, pb.Width - minx);
                    int y = r.Next(miny, pb.Height - miny);
                    //ps[i] = new Point(x, y);
                    ps.AddPosition(new Position_Point(x, y));
                    System.Console.Write(x);
                    System.Console.Write(",");
                    System.Console.Write(y);
                    System.Console.WriteLine(",");
                }
                System.Console.WriteLine();
            }
            //else
            //{
            //    ps = testData();
            //}

            IPositionSet convexPoints = convexhull.ConvexHull(ps);

            pb.Image = new Bitmap(pb.Width, pb.Height);
            Graphics g = Graphics.FromImage(pb.Image);

            convexPoints.InitToTraverseSet();

            g.Clear(Color.White);

            /*
             * for (int i = 0; i < ps.Length; i++)
             * {
             *  g.FillEllipse(Brushes.Black, ps[i].X - 2, pb.Height - ps[i].Y - 2, 4, 4);
             *  g.DrawString("(" + ps[i].X + "," + ps[i].Y + ")", Font, Brushes.Blue, ps[i].X, pb.Height - ps[i].Y);
             * }
             * for (int i = 0; i < convexPoints.Length; i++)
             * {
             *  if (i != convexPoints.Length - 1)
             *      g.DrawLine(new Pen(Color.Green), new PointF(convexPoints[i].X, pb.Height - convexPoints[i].Y), new PointF(convexPoints[i + 1].X, pb.Height - convexPoints[i + 1].Y));
             *  else
             *  {
             *      g.DrawLine(new Pen(Color.Green), new PointF(convexPoints[i].X, pb.Height - convexPoints[i].Y), new PointF(convexPoints[0].X, pb.Height - convexPoints[0].Y));
             *  }
             * }
             * */
            ps.InitToTraverseSet();
            IPosition p = ps.GetPosition();

            while (p != null)
            {
                g.FillEllipse(Brushes.Black, p.GetX() - 2, pb.Height - p.GetY() - 2, 4, 4);
                g.DrawString("(" + p.GetX() + "," + p.GetY() + ")", Font, Brushes.Blue, p.GetX(), pb.Height - p.GetY());
                p = ps.GetPosition();
            }
            IPosition p1 = convexPoints.GetPosition();
            IPosition p2 = convexPoints.GetPosition();

            while (p2 != null)
            {
                g.DrawLine(new Pen(Color.Green), new PointF(p1.GetX(), pb.Height - p1.GetY()), new PointF(p2.GetX(), pb.Height - p2.GetY()));
                p1 = p2;
                p2 = convexPoints.GetPosition();
            }
            convexPoints.InitToTraverseSet();
            p2 = convexPoints.GetPosition();
            g.DrawLine(new Pen(Color.Green), new PointF(p1.GetX(), pb.Height - p1.GetY()), new PointF(p2.GetX(), pb.Height - p2.GetY()));
        }
    public FarthestPair(Point2D[] pdarr)
    {
        this.bestDistance = double.NegativeInfinity;
        GrahamScan grahamScan = new GrahamScan(pdarr);

        if (pdarr.Length <= 1)
        {
            return;
        }
        int      num      = 0;
        Iterator iterator = grahamScan.hull().iterator();

        while (iterator.hasNext())
        {
            Point2D arg_46_0 = (Point2D)iterator.next();
            num++;
        }
        Point2D[] array     = new Point2D[num + 1];
        int       num2      = 1;
        Iterator  iterator2 = grahamScan.hull().iterator();

        while (iterator2.hasNext())
        {
            Point2D   point2D  = (Point2D)iterator2.next();
            Point2D[] arg_8A_0 = array;
            int       arg_8A_1 = num2;
            num2++;
            arg_8A_0[arg_8A_1] = point2D;
        }
        if (num == 1)
        {
            return;
        }
        if (num == 2)
        {
            this.best1        = array[1];
            this.best2        = array[2];
            this.bestDistance = this.best1.distanceTo(this.best2);
            return;
        }
        int num3 = 2;

        while (Point2D.area2(array[num], array[num3 + 1], array[1]) > Point2D.area2(array[num], array[num3], array[1]))
        {
            num3++;
        }
        int num4 = num3;

        for (int i = 1; i <= num3; i++)
        {
            if (array[i].distanceTo(array[num4]) > this.bestDistance)
            {
                this.best1        = array[i];
                this.best2        = array[num4];
                this.bestDistance = array[i].distanceTo(array[num4]);
            }
            while (num4 < num && Point2D.area2(array[i], array[num4 + 1], array[i + 1]) > Point2D.area2(array[i], array[num4], array[i + 1]))
            {
                num4++;
                double num5 = array[i].distanceTo(array[num4]);
                if (num5 > this.bestDistance)
                {
                    this.best1        = array[i];
                    this.best2        = array[num4];
                    this.bestDistance = array[i].distanceTo(array[num4]);
                }
            }
        }
    }
 public void GrahamScanNormalTestCase5000Points()
 {
     convexHullTester = new GrahamScan();
     Case5000Points();
 }
 public void GrahamScanTestCase10()
 {
     convexHullTester = new GrahamScan();
     Case10();
 }
 public void GrahamScanSpecialCaseConvexPolygon()
 {
     convexHullTester = new GrahamScan();
     SpecialCaseConvexPolygon();
 }
 public void GrahamScanSpecialCaseTriangle()
 {
     convexHullTester = new GrahamScan();
     SpecialCaseTriangle();
 }
 public void GrahamScanSpecialCase10SamePoints()
 {
     convexHullTester = new GrahamScan();
     SpecialCase10SamePoints();
 }
Exemple #21
0
    /**
     * Computes the farthest pair of points in the specified array of points.
     *
     * @param  points the array of points
     * @throws IllegalArgumentException if {@code points} is {@code null} or if any
     *         entry in {@code points[]} is {@code null}
     */
    public FarthestPair(Point2D[] points) {
        if (points == null) throw new IllegalArgumentException("constructor argument is null");
        for (int i = 0; i < points.length; i++) {
            if (points[i] == null) throw new IllegalArgumentException("array element " + i + " is null");
        }

        GrahamScan graham = new GrahamScan(points);

        // single point
        if (points.length <= 1) return;

        // number of points on the hull
        int m = 0;
        for (Point2D p : graham.hull())
            m++;

        // the hull, in counterclockwise order hull[1] to hull[m]
        Point2D[] hull = new Point2D[m+1];
        m = 1;
        for (Point2D p : graham.hull()) {
            hull[m++] = p;
        }
        m--;

        // all points are equal
        if (m == 1) return;

        // points are collinear
        if (m == 2) {
            best1 = hull[1];
            best2 = hull[2];
            bestDistanceSquared = best1.distanceSquaredTo(best2);
            return;
        }

        // k = farthest vertex from edge from hull[1] to hull[m]
        int k = 2;
        while (Point2D.area2(hull[m], hull[1], hull[k+1]) > Point2D.area2(hull[m], hull[1], hull[k])) {
            k++;
        }

        int j = k;
        for (int i = 1; i <= k && j <= m; i++) {
            // StdOut.println("hull[i] + " and " + hull[j] + " are antipodal");
            if (hull[i].distanceSquaredTo(hull[j]) > bestDistanceSquared) {
                best1 = hull[i];
                best2 = hull[j];
                bestDistanceSquared = hull[i].distanceSquaredTo(hull[j]);
            }
            while ((j < m) && Point2D.area2(hull[i], hull[i+1], hull[j+1]) > Point2D.area2(hull[i], hull[i+1], hull[j])) {
                j++;
                // StdOut.println(hull[i] + " and " + hull[j] + " are antipodal");
                double distanceSquared = hull[i].distanceSquaredTo(hull[j]);
                if (distanceSquared > bestDistanceSquared) {
                    best1 = hull[i];
                    best2 = hull[j];
                    bestDistanceSquared = hull[i].distanceSquaredTo(hull[j]);
                }
            }
        }
    }