How to simplify my code? (Searching for minimum and maximum coordinates in list of lines)

StackOverflow https://stackoverflow.com/questions/21844100

  •  13-10-2022
  •  | 
  •  

سؤال

I have code that is searching for minimum and maximum values in list of lines. I need this to find center of rectangle that is bounding my complicated drawing.

My part of code looks like this:

if (line.X1 < Min.X) Min.X = line.X1;
if (line.Y1 < Min.Y) Min.Y = line.Y1;
if (line.X2 < Min.X) Min.X = line.X2;
if (line.Y2 < Min.Y) Min.Y = line.Y2;

I dont like this ugly copy-paste code. How can I simplify this/make it more elegant?

هل كانت مفيدة؟

المحلول 2

Given the following populated variable:

List<Line> lines;

Get the X values and Y values:

var xValues = lines.SelectMany(line => new[] { line.X1, line.X2 });
var yValues = lines.SelectMany(line => new[] { line.Y1, line.Y2 });

Then get the minimum and maximum of each:

var leastX = xValues.Min();
var greatestX = xValues.Max();
var leastY = yValues.Min();
var greatestY = yValues.Max();

Note that this code isn't tested.

نصائح أخرى

How about something like this:

var xList = {line.X1, line.X2, ...};
var yList = {line.Y1, line.Y2, ...};

Min.X = xList.Min();
Min.Y = yList.Min();

Here is yet another option just using Math.Min:

Min.X = Math.Min(line.X2, Math.Min(line.X1, Min.X));
Min.Y = Math.Min(line.Y2, Math.Min(line.Y1, Min.Y));

The design of your classes already has some duplication; your Line class's definition of a Point is duplicated in X1, X2, etc.

If your design looks something like this:

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

class Line
{
    public Point Start { get; set; }
    public Point End { get; set; }

    public IEnumerable<Point> Endpoints
    {
        get
        {
            return new[] { Start, End };
        }
    }
}

You could implement your calculation like this:

class ExtremetiesDeterminer
{
    private IEnumerable<Point> endpoints;

    public Line DetermineBoundaries(IEnumerable<Line> complicatedShapeLines)
    {
        endpoints = complicatedShapeLines.SelectMany(line => line.Endpoints);

        return new Line
        {
            Start = FindExtremety(Enumerable.Min),
            End = FindExtremety(Enumerable.Max)
        };
    }

    private Point FindExtremety(
        SingleAxisExtremetyDeterminer findSingleAxisExtremety)
    {
        return new Point
        {
            X = findSingleAxisExtremety(endpoints, point => point.X),
            Y = findSingleAxisExtremety(endpoints, point => point.Y)
        };
    }

    public delegate int SingleAxisExtremetyDeterminer(
        IEnumerable<Point> points, Func<Point, int> getCoordinate);
}

Note that this reduces the duplication. You would probably want to adjust this depending on how this interacts with the rest of your code.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top