首页 > 解决方案 > 使用链表从具有 x 和 y 坐标的点形成三角形

问题描述

我有一个包含关于一个点的信息的linkedList:它的颜色,它的x 和y 坐标。

Color: Red  | X coordinate: 5   |  Y coordinate: 7
Color: Blue  | X coordinate: 6   |  Y coordinate: 5
Color: Red  | X coordinate: 2   |  Y coordinate: 4
Color: Blue  | X coordinate: 3   |  Y coordinate: 0
Color: Red  | X coordinate: 0   |  Y coordinate: 0
Color: Blue  | X coordinate: 0   |  Y coordinate: 5
Color: Yellow  | X coordinate: 1   |  Y coordinate: 4
Color: Yellow  | X coordinate: 2   |  Y coordinate: 3
Color: Yellow  | X coordinate: 1   |  Y coordinate: 1

我需要从匹配的颜色中找到一个三角形并找到它的周长。我该怎么做呢?

我的最终输出应该是:

Color: Red      |   Perimter: {}    |
Color: Blue     |   Perimeter: {}   |
Color: Yellow   |   Perimeter: {}   |

标签: c#linked-list

解决方案


尝试以下代码:

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

namespace ConsoleApplication107
{
    class Program
    {
        static void Main(string[] args)
        {

            List<Point> points = new List<Point>() {
                new Point() { Color = "Red", X = 5, Y = 7},
                new Point() { Color = "Blue", X = 6, Y = 5},
                new Point() { Color = "Red", X = 2, Y = 4},
                new Point() { Color = "Blue", X = 3, Y = 0},
                new Point() { Color = "Red", X = 0, Y = 0},
                new Point() { Color = "Blue", X = 0, Y = 5},
                new Point() { Color = "Yellow", X = 1, Y = 4},
                new Point() { Color = "Yellow", X = 2, Y = 3},
                new Point() { Color = "Yellow", X = 1, Y = 1}
            };

            //create link list
            LinkedList<Point> list = new LinkedList<Point>();
            foreach (Point point in points)
            {
                list.AddLast(point);
            }

            var results = list.GroupBy(x => x.Color).Select(x => new { color = x.Key, perimeter = x.Select(y => new { X = y.X, Y = y.Y }).ToList() }).ToList();

        }
    }
    public class Point
    {
        public string Color { get; set; }
        public int X { get; set; }
        public int Y { get; set; }
    }


}

推荐阅读