create a rect packing algorithm in csharp

Here's a simple implementation of a rectangular packing algorithm in C#:

main.cs
public class Rectangle
{
    public int Width { get; set; }
    public int Height { get; set; }

    public Rectangle(int width, int height)
    {
        Width = width;
        Height = height;
    }
}

public class Packer
{
    public List<Rectangle> PackRectangles(List<Rectangle> rectangles, int containerWidth, int containerHeight)
    {
        List<Rectangle> packedRectangles = new List<Rectangle>();

        // Sort rectangles by decreasing height to maximize the space usage
        rectangles = rectangles.OrderByDescending(r => r.Height).ToList();

        // Create an empty container rectangle
        Rectangle container = new Rectangle(containerWidth, containerHeight);

        // Loop through all rectangles and try to pack them within the container
        foreach (Rectangle rectangle in rectangles)
        {
            // Find a free space for the rectangle
            rectangle = FindFreeSpace(rectangle, container, packedRectangles);

            if (rectangle != null)
            {
                // Add the packed rectangle to the list
                packedRectangles.Add(rectangle);
            }
        }

        return packedRectangles;
    }

    private Rectangle FindFreeSpace(Rectangle rectangle, Rectangle container, List<Rectangle> packedRectangles)
    {
        // Start from the top-left corner of the container
        int x = 0, y = 0;

        // Loop through all positions in the container
        while (y + rectangle.Height <= container.Height)
        {
            x = 0;

            while (x + rectangle.Width <= container.Width)
            {
                // Check if the rectangle fits in the current position
                Rectangle space = new Rectangle(x, y, rectangle.Width, rectangle.Height);

                if (!IntersectsOtherRectangles(space, packedRectangles))
                {
                    // The rectangle fits, return the position
                    return space;
                }

                x++;
            }

            y++;
        }

        // The rectangle didn't fit, return null
        return null;
    }

    private bool IntersectsOtherRectangles(Rectangle rectangle, List<Rectangle> otherRectangles)
    {
        foreach (Rectangle other in otherRectangles)
        {
            if (rectangle.Intersects(other))
            {
                return true;
            }
        }

        return false;
    }
}
2419 chars
85 lines

This algorithm takes a list of rectangles, a container width and a container height, and returns a list of rectangles that are packed within the container without overlapping each other. The rectangles are sorted by decreasing height to maximize the space usage. The algorithm uses a brute-force approach to find a free space for each rectangle, by looping through all possible positions in the container.

gistlibby LogSnag