Skip to content

Instantly share code, notes, and snippets.

@lucasteles
Forked from WennderSantos/IsAValidPosition.cs
Last active November 1, 2018 19:21
Show Gist options
  • Select an option

  • Save lucasteles/7c89fad7e7137070757be0fb8531ce90 to your computer and use it in GitHub Desktop.

Select an option

Save lucasteles/7c89fad7e7137070757be0fb8531ce90 to your computer and use it in GitHub Desktop.
Check if a position is inside the bounds of a rectangle. O(1)
using static System.Console;
public class Rectangle
{
public Rectangle(int width, int heigth, (int x, int y) lowestPosition)
{
Width = width;
Heigth = heigth;
LowestPosition = lowestPosition;
}
public int Width { get; }
public int Heigth { get; }
public (int x, int y) LowestPosition { get; }
public bool IsThisAValidPosition((int x, int y) position) =>
position.x >= LowestPosition.x &&
position.x <= LowestPosition.x + Width &&
position.y >= LowestPosition.y &&
position.y <= LowestPosition.y + Heigth;
}
class Program
{
static void Main()
{
var rec = new Rectangle(3, 3, (1, 1));
var position1 = (4, 4);
var position2 = (0, 0);
var position3 = (1, 1);
var position4 = (2, 3);
var position5 = (3, 5);
WriteLine(rec.IsThisAValidPosition(position1)); //True
WriteLine(rec.IsThisAValidPosition(position2)); //False
WriteLine(rec.IsThisAValidPosition(position3)); //True
WriteLine(rec.IsThisAValidPosition(position4)); //True
WriteLine(rec.IsThisAValidPosition(position5)); //False
}
}
using static System.Console;
public class Rectangle
{
public Rectangle(int width, int heigth, Position lowestPosition)
{
Width = width;
Heigth = heigth;
LowestPosition = lowestPosition;
}
public int Width { get; }
public int Heigth { get; }
public Position LowestPosition { get; }
public bool IsThisAValidPosition(Position position)
{
var (x, y) = position;
var (lowerX, lowerY) = LowestPosition;
return
x >= lowerX &&
x <= lowerX + Width &&
y >= lowerY &&
y <= lowerY + Heigth;
}
public class Position
{
(int x, int y) Coords { get; }
public Position(int x, int y) =>
Coords = (x, y);
public void Deconstruct(out int x, out int y) => (x, y) = Coords;
}
}
class Program
{
static void Main(string[] args)
{
var rec = new Rectangle(3, 3, new Rectangle.Position(1, 1));
var position1 = new Rectangle.Position(4, 4);
var position2 = new Rectangle.Position(0, 0);
var position3 = new Rectangle.Position(1, 1);
var position4 = new Rectangle.Position(2, 3);
var position5 = new Rectangle.Position(3, 5);
WriteLine(rec.IsThisAValidPosition(position1)); //True
WriteLine(rec.IsThisAValidPosition(position2)); //False
WriteLine(rec.IsThisAValidPosition(position3)); //True
WriteLine(rec.IsThisAValidPosition(position4)); //True
WriteLine(rec.IsThisAValidPosition(position5)); //False
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment