Determine if two rectangles overlap each other

using System;

using System.Collections.Generic;

using System.Text;

using System.Text.RegularExpressions;

using System.IO;

 

namespace ConsoleApplication1

{

    public class Rectangle

    {

        public int topLeftx, topLefty, bottomRightx, bottomRighty;

        public Rectangle(int topLeftx, int topLefty, int bottomRightx, int bottomRighty)

        {

            if (topLeftx > bottomRightx || topLefty < bottomRighty)

            {

                throw new Exception("Incorrect coordinate values");

            }

            else

            {

                this.topLeftx = topLeftx;

                this.topLefty = topLefty;

                this.bottomRightx = bottomRightx;

                this.bottomRighty = bottomRighty;

            }

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            try

            {

                Rectangle r1 = new Rectangle(0, 0, 2, -1);

                Rectangle r2 = new Rectangle(3, 0, 4, -1);

                Console.WriteLine(CheckOverlap(r1, r2));

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

        }

        public static bool CheckOverlap(Rectangle r1, Rectangle r2)

        {

            bool overlap = true;

            if (r2.topLeftx > r1.bottomRightx || r2.bottomRightx < r1.topLeftx)

            {

                overlap = false;

            }

            else

            {

                if (r2.bottomRighty > r1.topLefty || r2.topLefty < r1.bottomRighty)

                {

                    overlap = false;

                }

            }

            return overlap;

        }

    }

}
 
False
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s