I'm trying to implement Improved Noise in my XNA game, but my Improved Noise function keeps returning 0.0f. It's the exact same code as Ken Perlin's (http://mrl.nyu.edu/~perlin/noise/), just ported to C#.
I've tried rewriting the class and even copy and pasting directly from the site (and then porting to C#, of course), but it just won't output any value but 0.
Here's the code that I'm using:
public class PerlinNoise
{
private int[] permutations = new int[512];
private Random random;
public PerlinNoise()
: this(Environment.TickCount)
{ }
public PerlinNoise(int seed)
{
random = new Random(seed);
for (int i = 0; i < 256; i++)
{
permutations[i] = i;
}
for (int i = 0; i < 256; i++)
{
int k = random.Next(256 - i) + i;
int l = permutations[i];
permutations[i] = permutations[k];
permutations[k] = l;
permutations[i + 256] = permutations[i];
}
}
private int fastfloor(float x)
{
return x > 0 ? (int)x : (int)x - 1;
}
private float fade(float t)
{
return t * t * t * (t * (t * 6 - 15) + 10);
}
private float lerp(float t, float a, float b)
{
return a + t * (b - a);
}
public float grad(int hash, float x, float y, float z)
{
int h = hash & 15;
float u = h < 8 ? x : y,
v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
}
public float noise3d(float x, float y, float z)
{
int X = fastfloor(x) & 0xff,
Y = fastfloor(y) & 0xff,
Z = fastfloor(z) & 0xff;
x -= fastfloor(x);
y -= fastfloor(y);
z -= fastfloor(z);
float u = fade(x);
float v = fade(y);
float w = fade(z);
int A = permutations[X] + Y, AA = permutations[A] + Z, AB = permutations[A + 1] + Z,
B = permutations[X + 1] + Y, BA = permutations[B] + Z, BB = permutations[B + 1] + Z;
return lerp(w, lerp(v, lerp(u, grad(permutations[AA], x, y, z),
grad(permutations[BA], x - 1, y, z)),
lerp(u, grad(permutations[AB], x, y - 1, z),
grad(permutations[BB], x - 1, y - 1, z))),
lerp(v, lerp(u, grad(permutations[AA + 1], x, y, z - 1),
grad(permutations[BA + 1], x - 1, y, z - 1)),
lerp(u, grad(permutations[AB + 1], x, y - 1, z - 1),
grad(permutations[BB + 1], x - 1, y - 1, z - 1))));
}
public float noise2d(float x, float y)
{
return noise3d(x, y, 0f);
}
} `
To test it, I simply did:
string[] args = Console.ReadLine().Split(' ');
PerlinNoise noise = new PerlinNoise();
int x = args[0];
int y = args[1];
int z = args[2];
Console.WriteLine(noise.noise3d(x, y, z));
And as I said above, it'll always output 0.
It seems to output 0.0f if all arguments are integral numbers. Change your testing code to
var input = Console.ReadLine()
.Split(' ')
.Select(s => float.Parse(s,
System.Globalization.CultureInfo.InvariantCulture))
.ToArray();
and try to enter, for example, 4234.2123 3123.12312 423.2434.
I'm not quite sure if it is desired behavior, but
x -= Math.Floor(x); // FIND RELATIVE X,Y,Z
y -= Math.Floor(y); // OF POINT IN CUBE.
z -= Math.Floor(z);
will always make x, y & z = 0 if they are integral numbers; fade(0.0f) is also always zero.
Multiply your inputs by (1 / MAX_VALUE) in your input case, just multiply by 1 / 256 or so, and never give it anything larger than that. When used in your game, multiply the input by (1 / MAXIMUM_CHOORD_VALUE).
Related
A 2 dimensional array with a size of NxN, composed of 1 and 0.
A neighbor is a 1 in the north / south / west / east of the index
Recursively find how many neighbors an index in the array has (neighbors that touch other neighbors are also included).
For the array I built I should get 6, but instead I get a stack overflow exception, and I don't get why.
Below is my 7x7 array, that for index 2, 5 should return the value of 6.
Example:
static void Main(string[] args)
{
int[,] arr = {
{ 0,0,0,1,0,0,0 },
{ 1,0,0,1,1,0,0 },
{ 0,0,0,0,1,1,0 },
{ 0,0,0,0,1,0,0 },
{ 0,0,0,0,0,0,0 },
{ 0,1,1,1,1,0,0 },
{ 1,0,0,1,0,0,0 },
};
Console.WriteLine(Recursive(arr,2,5));
Console.ReadLine();
}
Routine under test:
static public int Recursive(int[,] arr, int x, int y)
{
if (x < 0 || y < 0 || x > arr.GetLength(0) || y > arr.GetLength(1))
{
return 0;
}
// check if a 1 has neighbors
if (arr[x, y] == 1)
{
return 1 +
Recursive(arr, x - 1, y) +
Recursive(arr, x + 1, y) +
Recursive(arr, x, y - 1) +
Recursive(arr, x, y + 1);
}
else
{
return 0;
}
}
Please, note that when you compute Recursive(arr, x, y) you call both Recursive(arr, x - 1, y) and Recursive(arr, x + 1, y):
return 1 +
Recursive(arr, x - 1, y) + // <- both x - 1
Recursive(arr, x + 1, y) + // <- and x + 1
Recursive(arr, x, y - 1) +
Recursive(arr, x, y + 1);
On the next recursive call, when you try to compute Recursive(arr, x + 1, y) it calls Recursive(arr, x + 2, y) as well as Recursive(arr, x + 1 - 1, y) which is Recursive(arr, x, y). So you have a vicious circle: to compute Recursive(arr, x, y) you must compute Recursive(arr, x, y) and stack overflow as the the result.
The way out is to break the circle and don't let read the same cell again and again (we can just set it to 0 for this):
public static int Recursive(int[,] arr, int x, int y)
{
// out of the grid
if (x < 0 || y < 0 || x > arr.GetLength(0) || y > arr.GetLength(1))
return 0;
// empty cell
if (arr[x, y] == 0)
return 0;
// do not read the cell again! From now on treat it as an empty cell
arr[x, y] = 0;
int result = 1; // the cell itself
// let have a loop instead of four calls
for (int d = 0; d < 4; ++d)
result += Recursive(arr, x + (d - 2) % 2, y + (d - 1) % 2);
// Restore after the recursive call:
// let us do not damage arr with permanently setting cells to 0
// and return arr to its original state
arr[x, y] = 1;
return result;
}
Edit: non recursive solution, where we memorize in visited all the visited cells:
public static int Memoization(int[,] arr, int x, int y) {
if (x < 0 || y < 0 || x > arr.GetLength(0) || y > arr.GetLength(1))
return 0;
if (arr[x, y] == 0)
return 0;
int result = 0;
var agenda = new Queue<(int x, int y)>();
agenda.Enqueue((x, y));
var visited = new HashSet<(int x, int y)> { (x, y) };
while (agenda.Count > 0) {
result += 1;
var (oldX, oldY) = agenda.Dequeue();
for (int d = 0; d < 4; ++d) {
int newX = oldX + (d - 2) % 2;
int newY = oldY + (d - 1) % 2;
if (newX < 0 || newY < 0 || newX > arr.GetLength(0) || newY > arr.GetLength(1))
continue;
if (arr[newX, newY] == 0)
continue;
if (visited.Add((newX, newY)))
agenda.Enqueue((newX, newY));
}
}
return result;
}
Start by considering the simplest possible input. In this case it would be an array like
int[,] arr = { {1, 1 }}
I.e. an array consisting of only two items.
Start by the first left item, this is one, so next all neighbors recursed to.
All but the right neighbor is outside the array so will be ignored.
The right item is one, so all neighbors to this will be recursed to, including the left item.
Since you end up processing the left item again, you will continue the recursion until you run out of stack space.
The point here is that you need to keep track of all the points you have already visited. For example by using a HashSet<(int x, int y)>.
I need to interpolate whole 2d array in with c#.
I managed to write an interpolation class. It should work as intpl2 function of matlab.
slice: is the 2d array that going to be interpolated
xaxis: interpolated x axis
yaxis: interpolated y axis
It maps as
v0 v1 | v3 v2
EDIT: Solve the issue, but I am open to more elegant solution :)
public static float[,] ArrayBilinear(float[,] slice, float[] xaxis, float[] yaxis)
{
float[,] scaledSlice = new float[xaxis.Length, yaxis.Length];
double xscale = ((xaxis.Length - 1) / (slice.GetLength(0) - 1));
double yscale = ((yaxis.Length - 1) / (slice.GetLength(1) - 1));
for (int x = 0; x < scaledSlice.GetLength(0) ; x++)
{
for (int y = 0; y < scaledSlice.GetLength(1) ; y++)
{
float gx = ((float)x) / xaxis.Length * (slice.GetLength(0) - 1);
float gy = ((float)y) / yaxis.Length * (slice.GetLength(1) - 1);
int xInOriginal = (int)gx;
int yInOriginal = (int)gy;
double v0 = slice[xInOriginal, yInOriginal];
double v1 = slice[xInOriginal + 1, yInOriginal];
double v2 = slice[xInOriginal + 1, yInOriginal + 1];
double v3 = slice[xInOriginal, yInOriginal + 1];
double newValue = (1 - GetScale(xscale, x)) * (1 - GetScale(yscale, y)) * v0 + GetScale(xscale, x) * (1 - GetScale(yscale, y)) * v1 + GetScale(xscale, x) * GetScale(yscale, y) * v2 + (1 - GetScale(xscale, x)) * GetScale(yscale, y) * v3;
scaledSlice[x, y] = (float)newValue;
}
}
return scaledSlice;
}
private static double GetScale(double scale, int i)
{
if (i == 0)
return 0;
if (i % scale > 0)
return (i % scale) / scale;
return 1.0;
}
public static float[] LinSpace(float start, float stop, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if (length == 0) return new float[0];
if (length == 1) return new[] { stop };
float step = (stop - start) / (length - 1);
var data = new float[length];
for (int i = 0; i < data.Length; i++)
{
data[i] = start + i * step;
}
data[data.Length - 1] = stop;
return data;
}
Test with random 2d array
[Test]
public void testBilinearInterpolation()
{
float[,] array2D = new float[4, 4] { { 0, 0, 0, 5 }, { 1, 1, 4, 0 }, { 0, 1, 3, 1 }, { 0, 4, 0, 1 } };
var xaxes = LinSpace(0, 3, 10);
var yaxes = LinSpace(0, 3, 10);
var intepolatedarr = ArrayBilinear(array2D, xaxes , yaxes);
}
The interpolation result is wrong (Different from interp2 from matlab) I couldn't found why.
I'd like to make a scientific calculator in C#, but I didn't find gamma function to
calculate fractal factorials.
The function's description is below:
https://en.wikipedia.org/wiki/Gamma_function
How can I reach gamma function in C#?
Install the Math.NET package from nuget
Documentation on the Gamma Function : https://numerics.mathdotnet.com/Functions.html
The Math.NET package is indeed an easy way to get the gamma function. Please keep in mind that gamma(x) is equal to (x-1)!. So, gamma(4.1) = 6.813 while 4.1! = 27.932. To get 4.1! from gamma(4.1), you can multiply gamma(4.1) by 4.1, or simply take the gamma of 5.1 instead. (I see no need to show a bunch of digits of precision here.)
In C#:
using MathNet.Numerics; //at beginning of program
private double Factorial(double x)
{
double r = x;
r *= SpecialFunctions.Gamma(x);
return r;
//This could be simplified into:
//return x * SpecialFunctions.Gamma(x);
}
private double Factorial2(double x)
{
double r;
r = SpecialFunctions.Gamma(x + 1);
return r;
}
If for some reason you don't want to use Math.Net, you can write your own gamma function as follows:
static int g = 7;
static double[] p = {0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
Complex MyGamma(Complex z)
{
// Reflection formula
if (z.Real < 0.5)
{
return Math.PI / (Complex.Sin(Math.PI * z) * MyGamma(1 - z));
}
else
{
z -= 1;
Complex x = p[0];
for (var i = 1; i < g + 2; i++)
{
x += p[i] / (z + i);
}
Complex t = z + g + 0.5;
return Complex.Sqrt(2 * Math.PI) * (Complex.Pow(t, z + 0.5)) * Complex.Exp(-t) * x;
}
}
Note that you can replace the data type Complex with double and the Complex. functions with Math. if you don't need complex numbers, like so:
double MyGammaDouble(double z)
{
if (z < 0.5)
return Math.PI / (Math.Sin(Math.PI * z) * MyGammaDouble(1 - z));
z -= 1;
double x = p[0];
for (var i = 1; i < g + 2; i++)
x += p[i] / (z + i);
double t = z + g + 0.5;
return Math.Sqrt(2 * Math.PI) * (Math.Pow(t, z + 0.5)) * Math.Exp(-t) * x;
}
This is from an old wiki page (which has been replaced) but is copied here.
I have 2 lines. Both lines containing their 2 points of X and Y. This means they both have length.
I see 2 formulas, one using determinants and one using normal algebra. Which would be the most efficient to calculate and what does the formula looks like?
I'm having a hard time using matrices in code.
This is what I have so far, can it be more efficient?
public static Vector3 Intersect(Vector3 line1V1, Vector3 line1V2, Vector3 line2V1, Vector3 line2V2)
{
//Line1
float A1 = line1V2.Y - line1V1.Y;
float B1 = line1V1.X - line1V2.X;
float C1 = A1*line1V1.X + B1*line1V1.Y;
//Line2
float A2 = line2V2.Y - line2V1.Y;
float B2 = line2V1.X - line2V2.X;
float C2 = A2 * line2V1.X + B2 * line2V1.Y;
float det = A1*B2 - A2*B1;
if (det == 0)
{
return null;//parallel lines
}
else
{
float x = (B2*C1 - B1*C2)/det;
float y = (A1 * C2 - A2 * C1) / det;
return new Vector3(x,y,0);
}
}
Assuming you have two lines of the form Ax + By = C, you can find it pretty easily:
float delta = A1 * B2 - A2 * B1;
if (delta == 0)
throw new ArgumentException("Lines are parallel");
float x = (B2 * C1 - B1 * C2) / delta;
float y = (A1 * C2 - A2 * C1) / delta;
Pulled from here
I recently went back on paper to find a solution to this problem using basic algebra. We just need to solve the equations formed by the two lines and if a valid solution exist then there is an intersection.
You can check my Github repository for extended implementation handling potential precision issue with double and tests.
public struct Line
{
public double x1 { get; set; }
public double y1 { get; set; }
public double x2 { get; set; }
public double y2 { get; set; }
}
public struct Point
{
public double x { get; set; }
public double y { get; set; }
}
public class LineIntersection
{
// Returns Point of intersection if do intersect otherwise default Point (null)
public static Point FindIntersection(Line lineA, Line lineB, double tolerance = 0.001)
{
double x1 = lineA.x1, y1 = lineA.y1;
double x2 = lineA.x2, y2 = lineA.y2;
double x3 = lineB.x1, y3 = lineB.y1;
double x4 = lineB.x2, y4 = lineB.y2;
// equations of the form x=c (two vertical lines) with overlapping
if (Math.Abs(x1 - x2) < tolerance && Math.Abs(x3 - x4) < tolerance && Math.Abs(x1 - x3) < tolerance)
{
throw new Exception("Both lines overlap vertically, ambiguous intersection points.");
}
//equations of the form y=c (two horizontal lines) with overlapping
if (Math.Abs(y1 - y2) < tolerance && Math.Abs(y3 - y4) < tolerance && Math.Abs(y1 - y3) < tolerance)
{
throw new Exception("Both lines overlap horizontally, ambiguous intersection points.");
}
//equations of the form x=c (two vertical parallel lines)
if (Math.Abs(x1 - x2) < tolerance && Math.Abs(x3 - x4) < tolerance)
{
//return default (no intersection)
return default(Point);
}
//equations of the form y=c (two horizontal parallel lines)
if (Math.Abs(y1 - y2) < tolerance && Math.Abs(y3 - y4) < tolerance)
{
//return default (no intersection)
return default(Point);
}
//general equation of line is y = mx + c where m is the slope
//assume equation of line 1 as y1 = m1x1 + c1
//=> -m1x1 + y1 = c1 ----(1)
//assume equation of line 2 as y2 = m2x2 + c2
//=> -m2x2 + y2 = c2 -----(2)
//if line 1 and 2 intersect then x1=x2=x & y1=y2=y where (x,y) is the intersection point
//so we will get below two equations
//-m1x + y = c1 --------(3)
//-m2x + y = c2 --------(4)
double x, y;
//lineA is vertical x1 = x2
//slope will be infinity
//so lets derive another solution
if (Math.Abs(x1 - x2) < tolerance)
{
//compute slope of line 2 (m2) and c2
double m2 = (y4 - y3) / (x4 - x3);
double c2 = -m2 * x3 + y3;
//equation of vertical line is x = c
//if line 1 and 2 intersect then x1=c1=x
//subsitute x=x1 in (4) => -m2x1 + y = c2
// => y = c2 + m2x1
x = x1;
y = c2 + m2 * x1;
}
//lineB is vertical x3 = x4
//slope will be infinity
//so lets derive another solution
else if (Math.Abs(x3 - x4) < tolerance)
{
//compute slope of line 1 (m1) and c2
double m1 = (y2 - y1) / (x2 - x1);
double c1 = -m1 * x1 + y1;
//equation of vertical line is x = c
//if line 1 and 2 intersect then x3=c3=x
//subsitute x=x3 in (3) => -m1x3 + y = c1
// => y = c1 + m1x3
x = x3;
y = c1 + m1 * x3;
}
//lineA & lineB are not vertical
//(could be horizontal we can handle it with slope = 0)
else
{
//compute slope of line 1 (m1) and c2
double m1 = (y2 - y1) / (x2 - x1);
double c1 = -m1 * x1 + y1;
//compute slope of line 2 (m2) and c2
double m2 = (y4 - y3) / (x4 - x3);
double c2 = -m2 * x3 + y3;
//solving equations (3) & (4) => x = (c1-c2)/(m2-m1)
//plugging x value in equation (4) => y = c2 + m2 * x
x = (c1 - c2) / (m2 - m1);
y = c2 + m2 * x;
//verify by plugging intersection point (x, y)
//in orginal equations (1) & (2) to see if they intersect
//otherwise x,y values will not be finite and will fail this check
if (!(Math.Abs(-m1 * x + y - c1) < tolerance
&& Math.Abs(-m2 * x + y - c2) < tolerance))
{
//return default (no intersection)
return default(Point);
}
}
//x,y can intersect outside the line segment since line is infinitely long
//so finally check if x, y is within both the line segments
if (IsInsideLine(lineA, x, y) &&
IsInsideLine(lineB, x, y))
{
return new Point { x = x, y = y };
}
//return default (no intersection)
return default(Point);
}
// Returns true if given point(x,y) is inside the given line segment
private static bool IsInsideLine(Line line, double x, double y)
{
return (x >= line.x1 && x <= line.x2
|| x >= line.x2 && x <= line.x1)
&& (y >= line.y1 && y <= line.y2
|| y >= line.y2 && y <= line.y1);
}
}
How to find intersection of two lines/segments/ray with rectangle
public class LineEquation{
public LineEquation(Point start, Point end){
Start = start;
End = end;
IsVertical = Math.Abs(End.X - start.X) < 0.00001f;
M = (End.Y - Start.Y)/(End.X - Start.X);
A = -M;
B = 1;
C = Start.Y - M*Start.X;
}
public bool IsVertical { get; private set; }
public double M { get; private set; }
public Point Start { get; private set; }
public Point End { get; private set; }
public double A { get; private set; }
public double B { get; private set; }
public double C { get; private set; }
public bool IntersectsWithLine(LineEquation otherLine, out Point intersectionPoint){
intersectionPoint = new Point(0, 0);
if (IsVertical && otherLine.IsVertical)
return false;
if (IsVertical || otherLine.IsVertical){
intersectionPoint = GetIntersectionPointIfOneIsVertical(otherLine, this);
return true;
}
double delta = A*otherLine.B - otherLine.A*B;
bool hasIntersection = Math.Abs(delta - 0) > 0.0001f;
if (hasIntersection){
double x = (otherLine.B*C - B*otherLine.C)/delta;
double y = (A*otherLine.C - otherLine.A*C)/delta;
intersectionPoint = new Point(x, y);
}
return hasIntersection;
}
private static Point GetIntersectionPointIfOneIsVertical(LineEquation line1, LineEquation line2){
LineEquation verticalLine = line2.IsVertical ? line2 : line1;
LineEquation nonVerticalLine = line2.IsVertical ? line1 : line2;
double y = (verticalLine.Start.X - nonVerticalLine.Start.X)*
(nonVerticalLine.End.Y - nonVerticalLine.Start.Y)/
((nonVerticalLine.End.X - nonVerticalLine.Start.X)) +
nonVerticalLine.Start.Y;
double x = line1.IsVertical ? line1.Start.X : line2.Start.X;
return new Point(x, y);
}
public bool IntersectWithSegementOfLine(LineEquation otherLine, out Point intersectionPoint){
bool hasIntersection = IntersectsWithLine(otherLine, out intersectionPoint);
if (hasIntersection)
return intersectionPoint.IsBetweenTwoPoints(otherLine.Start, otherLine.End);
return false;
}
public bool GetIntersectionLineForRay(Rect rectangle, out LineEquation intersectionLine){
if (Start == End){
intersectionLine = null;
return false;
}
IEnumerable<LineEquation> lines = rectangle.GetLinesForRectangle();
intersectionLine = new LineEquation(new Point(0, 0), new Point(0, 0));
var intersections = new Dictionary<LineEquation, Point>();
foreach (LineEquation equation in lines){
Point point;
if (IntersectWithSegementOfLine(equation, out point))
intersections[equation] = point;
}
if (!intersections.Any())
return false;
var intersectionPoints = new SortedDictionary<double, Point>();
foreach (var intersection in intersections){
if (End.IsBetweenTwoPoints(Start, intersection.Value) ||
intersection.Value.IsBetweenTwoPoints(Start, End)){
double distanceToPoint = Start.DistanceToPoint(intersection.Value);
intersectionPoints[distanceToPoint] = intersection.Value;
}
}
if (intersectionPoints.Count == 1){
Point endPoint = intersectionPoints.First().Value;
intersectionLine = new LineEquation(Start, endPoint);
return true;
}
if (intersectionPoints.Count == 2){
Point start = intersectionPoints.First().Value;
Point end = intersectionPoints.Last().Value;
intersectionLine = new LineEquation(start, end);
return true;
}
return false;
}
public override string ToString(){
return "[" + Start + "], [" + End + "]";
}
}
full sample is described [here][1]
I've solved Polygon problem problem at interviewstreet, but it seems too slow. What is the best solution to the problem?
There are N points on X-Y plane with integer coordinates (xi, yi). You are given a set of polygons with all of its edges parallel to the axes (in other words, all angles of the polygons are 90 degree angles and all lines are in the cardinal directions. There are no diagonals). For each polygon your program should find the number of points lying inside it (A point located on the border of polygon is also considered to be inside the polygon).
Input:
First line two integers N and Q. Next line contains N space separated integer coordinates (xi,yi). Q queries follow. Each query consists of a single integer Mi in the first line, followed by Mi space separated integer coordinates (x[i][j],y[i][j]) specifying the boundary of the query polygon in clock-wise order.
Polygon is an alternating sequence of vertical line segments and horizontal line segments.
Polygon has Mi edges, where (x[i][j],y[i][j]) is connected to (x[i][(j+1)%Mi], y[i][(j+1)%Mi].
For each 0 <= j < Mi, either x[i][(j+1)%Mi] == x[i][j] or y[i][(j+1)%Mi] == y[i][j] but not both.
It is also guaranteed that the polygon is not self-intersecting.
Output:
For each query output the number of points inside the query polygon in a separate line.
Sample Input #1:
16 2
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 3
3 0
3 1
3 2
3 3
8
0 0
0 1
1 1
1 2
0 2
0 3
3 3
3 0
4
0 0
0 1
1 1
1 0
Sample Output #1:
16
4
Sample Input #2:
6 1
1 1
3 3
3 5
5 2
6 3
7 4
10
1 3
1 6
4 6
4 3
6 3
6 1
4 1
4 2
3 2
3 3
Sample Output #2:
4
Constraints:
1 <= N <= 20,000
1 <= Q <= 20,000
4 <= Mi <= 20
Each co-ordinate would have a value of atmost 200,000
I am interested in solutions in mentioned languages or pseudo code.
EDIT: here is my code but it's O(n^2)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Polygon
{
// avoding System.Drawing dependency
public struct Point
{
public int X { get; private set; }
public int Y { get; private set; }
public Point(int x, int y)
: this()
{
X = x;
Y = y;
}
public override int GetHashCode()
{
return X ^ Y;
}
public override bool Equals(Object obj)
{
return obj is Point && this == (Point)obj;
}
public static bool operator ==(Point a, Point b)
{
return a.X == b.X && a.Y == b.Y;
}
public static bool operator !=(Point a, Point b)
{
return !(a == b);
}
}
public class Solution
{
static void Main(string[] args)
{
BasicTestCase();
CustomTestCase();
// to read from STDIN
//string firstParamsLine = Console.ReadLine();
//var separator = new char[] { ' ' };
//var firstParams = firstParamsLine.Split(separator);
//int N = int.Parse(firstParams[0]);
//int Q = int.Parse(firstParams[1]);
//List<Point> points = new List<Point>(N);
//for (int i = 0; i < N; i++)
//{
// var coordinates = Console.ReadLine().Split(separator);
// points.Add(new Point(int.Parse(coordinates[0]), int.Parse(coordinates[1])));
//}
//var polygons = new List<List<Point>>(Q); // to reduce realocation
//for (int i = 0; i < Q; i++)
//{
// var firstQ = Console.ReadLine().Split(separator);
// int coordinatesLength = int.Parse(firstQ[0]);
// var polygon = new List<Point>(coordinatesLength);
// for (int j = 0; j < coordinatesLength; j++)
// {
// var coordinates = Console.ReadLine().Split(separator);
// polygon.Add(new Point(int.Parse(coordinates[0]), int.Parse(coordinates[1])));
// }
// polygons.Add(polygon);
//}
//foreach (var polygon in polygons)
//{
// Console.WriteLine(CountPointsInPolygon(points, polygon));
//}
}
private static void BasicTestCase()
{
List<Point> points = new List<Point>(){ new Point(0, 0),
new Point(0, 1),
new Point(0, 2),
new Point(0, 3),
new Point(1, 0),
new Point(1, 1),
new Point(1, 2),
new Point(1, 3),
new Point(2, 0),
new Point(2, 1),
new Point(2, 2),
new Point(2, 3),
new Point(3, 0),
new Point(3, 1),
new Point(3, 2),
new Point(3, 3) };
List<Point> polygon1 = new List<Point>(){ new Point(0, 0),
new Point(0, 1),
new Point(2, 1),
new Point(2, 2),
new Point(0, 2),
new Point(0, 3),
new Point(3, 3),
new Point(3, 0)};
List<Point> polygon2 = new List<Point>(){ new Point(0, 0),
new Point(0, 1),
new Point(1, 1),
new Point(1, 0),};
Console.WriteLine(CountPointsInPolygon(points, polygon1));
Console.WriteLine(CountPointsInPolygon(points, polygon2));
List<Point> points2 = new List<Point>(){new Point(1, 1),
new Point(3, 3),
new Point(3, 5),
new Point(5, 2),
new Point(6, 3),
new Point(7, 4),};
List<Point> polygon3 = new List<Point>(){ new Point(1, 3),
new Point(1, 6),
new Point(4, 6),
new Point(4, 3),
new Point(6, 3),
new Point(6, 1),
new Point(4, 1),
new Point(4, 2),
new Point(3, 2),
new Point(3, 3),};
Console.WriteLine(CountPointsInPolygon(points2, polygon3));
}
private static void CustomTestCase()
{
// generated 20 000 points and polygons
using (StreamReader file = new StreamReader(#"in3.txt"))
{
string firstParamsLine = file.ReadLine();
var separator = new char[] { ' ' };
var firstParams = firstParamsLine.Split(separator);
int N = int.Parse(firstParams[0]);
int Q = int.Parse(firstParams[1]);
List<Point> pointsFromFile = new List<Point>(N);
for (int i = 0; i < N; i++)
{
var coordinates = file.ReadLine().Split(separator);
pointsFromFile.Add(new Point(int.Parse(coordinates[0]), int.Parse(coordinates[1])));
}
var polygons = new List<List<Point>>(Q); // to reduce realocation
for (int i = 0; i < Q; i++)
{
var firstQ = file.ReadLine().Split(separator);
int coordinatesLength = int.Parse(firstQ[0]);
var polygon = new List<Point>(coordinatesLength);
for (int j = 0; j < coordinatesLength; j++)
{
var coordinates = file.ReadLine().Split(separator);
polygon.Add(new Point(int.Parse(coordinates[0]), int.Parse(coordinates[1])));
}
polygons.Add(polygon);
}
foreach (var polygon in polygons)
{
Console.WriteLine(CountPointsInPolygon(pointsFromFile, polygon));
}
}
}
public static int CountPointsInPolygon(List<Point> points, List<Point> polygon)
{
// TODO input check
polygon.Add(polygon[0]); // for simlicity
// check if any point is outside of the bounding box of the polygon
var minXpolygon = polygon.Min(p => p.X);
var maxXpolygon = polygon.Max(p => p.X);
var minYpolygon = polygon.Min(p => p.Y);
var maxYpolygon = polygon.Max(p => p.Y);
// ray casting algorithm (form max X moving to point)
int insidePolygon = 0;
foreach (var point in points)
{
if (point.X >= minXpolygon && point.X <= maxXpolygon && point.Y >= minYpolygon && point.Y <= maxYpolygon)
{ // now points are inside the bounding box
isPointsInside(polygon, point, ref insidePolygon);
} // else outside
}
return insidePolygon;
}
private static void isPointsInside(List<Point> polygon, Point point, ref int insidePolygon)
{
int intersections = 0;
for (int i = 0; i < polygon.Count - 1; i++)
{
if (polygon[i] == point)
{
insidePolygon++;
return;
}
if (point.isOnEdge(polygon[i], polygon[i + 1]))
{
insidePolygon++;
return;
}
if (Helper.areIntersecting(polygon[i], polygon[i + 1], point))
{
intersections++;
}
}
if (intersections % 2 != 0)
{
insidePolygon++;
}
}
}
static class Helper
{
public static bool isOnEdge(this Point point, Point first, Point next)
{
// onVertical
if (point.X == first.X && point.X == next.X && point.Y.InRange(first.Y, next.Y))
{
return true;
}
//onHorizontal
if (point.Y == first.Y && point.Y == next.Y && point.X.InRange(first.X, next.X))
{
return true;
}
return false;
}
public static bool InRange(this int value, int first, int second)
{
if (first <= second)
{
return value >= first && value <= second;
}
else
{
return value >= second && value <= first;
}
}
public static bool areIntersecting(Point polygonPoint1, Point polygonPoint2, Point vector2End)
{
// "move" ray up for 0.5 to avoid problem with parallel edges
if (vector2End.X < polygonPoint1.X )
{
var y = (vector2End.Y + 0.5);
var first = polygonPoint1.Y;
var second = polygonPoint2.Y;
if (first <= second)
{
return y >= first && y <= second;
}
else
{
return y >= second && y <= first;
}
}
return false;
}
}
}
A faster solution is to place the points into a quadtree.
A region quadtree might be easier to code, but a point quadtree is probably faster. If using a region quadtree then it can help to stop subdividing the quadtree when the number of points in a quad falls below a threshold (say 16 points)
Each quad stores the number of points it contains, plus either a list of coordinates (for leaf nodes) or pointers to smaller quads. (You can omit the list of coordinates when the size of the quad reaches 1 as they must all be coincident)
To count the points inside the polygon you look at the largest quad that represents the root of the quadtree.
Clip the polygon to the edges of the quad
If the polygon does not overlap the quad then return 0
If this is a quad of size 1x1 then return the number of points in the quad
If the polygon totally encircles the quad then return the number of points in the quad.
If this is a leaf node then test each point with the plumb line algorithm
Otherwise recursively count the points in each child quad
(If a quad only has one non-empty child then you can skip steps 1,2,3,4,5 to go a little faster)
(The tests in 2 and 4 do not have to be totally accurate)
Does trapezoidal decomposition work for you?
I refer you to Jordan Curve Theorem and the Plumb Line Algorithm.
The relevant pseudocode is
int crossings = 0
for (each line segment of the polygon)
if (ray down from (x,y) crosses segment)
crossings++;
if (crossings is odd)
return (inside);
else return (outside);
I would try casting a ray up from the bottom to each point, tracking where it crossed into the polygon (passing a right-to-left segment) or back out of the polygon (passing a left-to-right segment). Something like this:
count := 0
For each point (px, py):
inside := false
For each query line (x0, y0) -> (x1, y1) where y0 = y1
if inside
if x0 <= px < x1 and py > y0
inside = false
else
if x1 <= px <= x0 and py >= y0
inside = true
if inside
count++
The > vs. >= in the two cases is so that a point on the upper edge is considered inside. I haven't actually coded this up to see if it works, but I think the approach is sound.
Here is the solution from authors - a bit obfuscated, isn't it?
#include <iostream>
#include <ctime>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <ctime>
using namespace std;
typedef long long int64;
const int N = 100000, X = 2000000001;
const int Q = 100000, PQ = 20;
struct Point {
int x, y, idx;
Point(int _x = 0, int _y = 0, int _idx = 0) {
x = _x;
y = _y;
idx = _idx;
}
} arr_x[N], arr_y[N];
struct VLineSegment {
int x, y1, y2, idx, sign;
VLineSegment(int _x = 0, int _y1 = 0, int _y2 = 0, int _sign = 1, int _idx = 0) {
x = _x;
y1 = _y1;
y2 = _y2;
sign = _sign;
idx = _idx;
}
bool operator<(const VLineSegment& v) const {
return x < v.x;
}
} segs[Q * PQ];
struct TreeNode {
int idx1, idx2, cnt;
TreeNode *left, *right;
TreeNode() { left = right = 0; cnt = 0; }
~TreeNode() { if(left) delete left; if(right) delete right; }
void update_stat() {
cnt = left->cnt + right->cnt;
}
void build(Point* arr, int from, int to, bool empty) {
idx1 = from;
idx2 = to;
if(from == to) {
if(!empty) {
cnt = 1;
} else {
cnt = 0;
}
} else {
left = new TreeNode();
right = new TreeNode();
int mid = (from + to) / 2;
left->build(arr, from, mid, empty);
right->build(arr, mid + 1, to, empty);
update_stat();
}
}
void update(Point& p, bool add) {
if(p.idx >= idx1 && p.idx <= idx2) {
if(idx1 != idx2) {
left->update(p, add);
right->update(p, add);
update_stat();
} else {
if(add) {
cnt = 1;
} else {
cnt = 0;
}
}
}
}
int query(int ya, int yb) {
int y1 = arr_y[idx1].y, y2 = arr_y[idx2].y;
if(ya <= y1 && y2 <= yb) {
return cnt;
} else if(max(ya, y1) <= min(yb, y2)) {
return left->query(ya, yb) + right->query(ya, yb);
}
return 0;
}
};
bool cmp_x(const Point& a, const Point& b) {
return a.x < b.x;
}
bool cmp_y(const Point& a, const Point& b) {
return a.y < b.y;
}
void calc_ys(int x1, int y1, int x2, int y2, int x3, int sign, int& ya, int& yb) {
if(x2 < x3) {
yb = 2 * y2 - sign;
} else {
yb = 2 * y2 + sign;
}
if(x2 < x1) {
ya = 2 * y1 + sign;
} else {
ya = 2 * y1 - sign;
}
}
bool process_polygon(int* x, int* y, int cnt, int &idx, int i) {
for(int j = 0; j < cnt; j ++) {
//cerr << x[(j + 1) % cnt] - x[j] << "," << y[(j + 1) % cnt] - y[j] << endl;
if(x[j] == x[(j + 1) % cnt]) {
int _x, y1, y2, sign;
if(y[j] < y[(j + 1) % cnt]) {
_x = x[j] * 2 - 1;
sign = -1;
calc_ys(x[(j + cnt - 1) % cnt], y[j], x[j], y[(j + 1) % cnt], x[(j + 2) % cnt], sign, y1, y2);
} else {
_x = x[j] * 2 + 1;
sign = 1;
calc_ys(x[(j + 2) % cnt], y[(j + 2) % cnt], x[j], y[j], x[(j + cnt - 1) % cnt], sign, y1, y2);
}
segs[idx++] = VLineSegment(_x, y1, y2, sign, i);
}
}
}
int results[Q];
int n, q, c;
int main() {
int cl = clock();
cin >> n >> q;
for(int i = 0; i < n; i ++) {
cin >> arr_y[i].x >> arr_y[i].y;
arr_y[i].x *= 2;
arr_y[i].y *= 2;
}
int idx = 0, cnt, x[PQ], y[PQ];
for(int i = 0; i < q; i ++) {
cin >> cnt;
for(int j = 0; j < cnt; j ++) cin >> x[j] >> y[j];
process_polygon(x, y, cnt, idx, i);
}
sort(segs, segs + idx);
memset(results, 0, sizeof results);
sort(arr_y, arr_y + n, cmp_y);
for(int i = 0; i < n; i ++) {
arr_y[i].idx = i;
arr_x[i] = arr_y[i];
}
sort(arr_x, arr_x + n, cmp_x);
TreeNode tleft;
tleft.build(arr_y, 0, n - 1, true);
for(int i = 0, j = 0; i < idx; i ++) {
for(; j < n && arr_x[j].x <= segs[i].x; j ++) {
tleft.update(arr_x[j], true);
}
int qcnt = tleft.query(segs[i].y1, segs[i].y2);
//cerr << segs[i].x * 0.5 << ", " << segs[i].y1 * 0.5 << ", " << segs[i].y2 * 0.5 << " = " << qcnt << " * " << segs[i].sign << endl;
results[segs[i].idx] += qcnt * segs[i].sign;
}
for(int i = 0; i < q; i ++) {
cout << results[i] << endl;
}
cerr << (clock() - cl) * 0.001 << endl;
return 0;
}