简体   繁体   中英

Find intersect with not an exact point

I have a problem. I created this class to find all the shared edges of a hexagon:

public class HexagonRegistryList
{
    public int HexagonNum { get; set; }
    public float x1 { get; set; }
    public float y1 { get; set; }
    public float x2 { get; set; }
    public float y2 { get; set; }
    public float x3 { get; set; }
    public float y3 { get; set; }
    public float x4 { get; set; }
    public float y4 { get; set; }
    public float x5 { get; set; }
    public float y5 { get; set; }
    public float x6 { get; set; }
    public float y6 { get; set; }
    public int ShapeNum { get; set; }

    public HexagonRegistryList()
    {
        this.AdjacentShapeNumbers = new List<int>();
    }

    public List<int> AdjacentShapeNumbers { get; set; }

    public IEnumerable<(float x, float y)> GetPoints()
    {
        yield return (x1, y1);
        yield return (x2, y2);
        yield return (x3, y3);
        yield return (x4, y4);
        yield return (x5, y5);
        yield return (x6, y6);
    }


    public bool IsAdjacentTo(HexagonRegistryList other)
    {
        var isAdjacentTo =
                    GetPoints().Intersect(other.GetPoints()).Count() >= 2;
        if (isAdjacentTo)
        {
            if (other.ShapeNum != 0)
            {
                AdjacentShapeNumbers.Add(other.ShapeNum);
            }
        }
        return isAdjacentTo;
    }
}

But now I want something, so the values don't have to be exactly the same, but that they can have a difference of max 1. So when I compare 350 with 350, it could also be 350 with 349, or 350 with 351. Can someone help me with that?

Define a custom comparer:

public struct PointComparer : IEqualityComparer<(float x, float y)>
{
    public bool Equals((float x, float y) p1, (float x, float y) p2)
    {
        return Math.Abs(p1.x - p2.x) < 1f && Math.Abs(p1.y - p2.y) < 1f;
    }

    public int GetHashCode((float x, float y) obj)
    {
        return 1;
    }
}

Then pass it to Intersect method

GetPoints().Intersect(other.GetPoints(), new PointComparer())

You would need to create an implementation which uses a bounded absolute difference to determine proximity; this can be done as follows.

var DIFF_THRESHOLD = 1.0f;
var DIFF_THRESHOLD_SQUARE = DIFF_THRESHOLD * DIFF_THRESHOLD;

private IsCloseTo(float x1, float y1, float x2, float y2)
{
    var EuklideanDistance
        = ( x1 - x2 ) * ( x1 - x2 ) +  ( y1 - y2 ) * ( y1 - y2 );
    return EuklidenDistance <= DIFF_THRESHOLD_SQUARE;
}

Then you could use Linq to determine the number of points which are close to each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM