point inside a polygon with edges parallel to the axes - c#

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;
}

Related

Is there a way to increase the maximum number of stack frames in Visual Studio (or avoid exceeding it otherwise)?

I am applying the so-called Wolff algorithm to simulate a very large square lattice Ising model at critical temperature in Visual Studio C#. I start out with all lattice sites randomly filled with either -1 or +1, and then the Wolff algorithm is applied for a certain number of times. Basically, per application, it randomly activates one lattice site and it checks if neighbouring lattice sites are of the same spin (the same value as the initially selected site) and with a certain chance it gets activated as well. The process is repeated for every new activation, so the activated lattice sites form a connected subset of the full lattice. All activated spins flip (*= -1). This is done a large number of times.
This is the class I use:
class WolffAlgorithm
{
public sbyte[,] Data;
public int DimX;
public int DimY;
public double ExpMin2BetaJ;
private sbyte[,] transl = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
public WolffAlgorithm(sbyte[,] data, double beta, double j)
{
Data = data;
DimX = data.GetLength(0);
DimY = data.GetLength(1);
ExpMin2BetaJ = Math.Exp(- 2 * beta * j);
}
public void Run(int n, int print_n)
{
Random random = new Random();
DateTime t0 = DateTime.Now;
int act = 0;
for (int i = 0; i < n; i++)
{
int x = random.Next(0, DimX);
int y = random.Next(0, DimY);
int[] pos = { x, y };
List<int[]> activations = new List<int[]>();
activations.Add(pos);
sbyte up_down = Data[x, y];
Data[x, y] *= -1;
CheckActivation(random, up_down, activations, x, y);
act += activations.Count;
if ((i + 1) % print_n == 0)
{
DateTime t1 = DateTime.Now;
Console.WriteLine("n: " + i + ", act: " + act + ", time: " + (t1 - t0).TotalSeconds + " sec");
t0 = t1;
act = 0;
}
}
}
private void CheckActivation(Random random, sbyte up_down, List<int[]> activations, int x, int y)
{
for (int i = 0; i < transl.GetLength(0); i++)
{
int tr_x = (x + transl[i, 0]) % DimX;
if (tr_x < 0) tr_x += DimX;
int tr_y = (y + transl[i, 1]) % DimY;
if (tr_y < 0) tr_y += DimY;
if (Data[tr_x, tr_y] != up_down)
{
continue;
}
if (random.NextDouble() < 1 - ExpMin2BetaJ)
{
int[] new_activation = { tr_x, tr_y };
activations.Add(new_activation);
Data[tr_x, tr_y] *= -1;
CheckActivation(random, up_down, activations, tr_x, tr_y);
}
}
}
}
When I approach the equilibrium configuration, the activated groups become so large, that the recursive function exceeds the maximum number of stack frames (apparently 5000), triggering the StackOverflowException (fitting for my first post on StackOverflow.com, I guess haha).
What I've tried:
I have tried adjusting the maximum number of stack frames like what is proposed here: https://www.poppastring.com/blog/adjusting-stackframes-in-visual-studio
This did not work for me.
I have also tried to reduce the number of stack frames needed by just copying the same function in the function (however ugly this looks):
private void CheckActivation2(Random random, sbyte up_down, List<int[]> activations, int x, int y)
{
for (int i = 0; i < transl.GetLength(0); i++)
{
int tr_x = (x + transl[i, 0]) % DimX;
if (tr_x < 0) tr_x += DimX;
int tr_y = (y + transl[i, 1]) % DimY;
if (tr_y < 0) tr_y += DimY;
if (Data[tr_x, tr_y] != up_down)
{
continue;
}
if (random.NextDouble() < 1 - ExpMin2BetaJ)
{
int[] new_activation = { tr_x, tr_y };
activations.Add(new_activation);
Data[tr_x, tr_y] *= -1;
for (int i2 = 0; i2 < transl.GetLength(0); i2++)
{
int tr_x2 = (tr_x + transl[i2, 0]) % DimX;
if (tr_x2 < 0) tr_x2 += DimX;
int tr_y2 = (tr_y + transl[i2, 1]) % DimY;
if (tr_y2 < 0) tr_y2 += DimY;
if (Data[tr_x2, tr_y2] != up_down)
{
continue;
}
if (random.NextDouble() < 1 - ExpMin2BetaJ)
{
int[] new_activation2 = { tr_x2, tr_y2 };
activations.Add(new_activation2);
Data[tr_x2, tr_y2] *= -1;
CheckActivation2(random, up_down, activations, tr_x2, tr_y2);
}
}
}
}
}
This works, but it is not enough and I don't know how to scale this elegantly by an arbitrary number of times, without calling the function recursively.
I hope anyone can help me with this!

How to yield coordinate pairs from a start point to an end point?

I want to create coordinate pairs that demonstrates a path between two points. First if it is available the function should make a diagonal path then the remaining coordinates should be either vertical or horizontal.
I calculated the absolute X and Y values between two points. Then if X or Y is greater than zero, the function decreases it and yields the result.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var start = new Point(10, 10);
var end = new Point(5, 3);
var coordinates = new List<Point>(Coordinates(start, end));
foreach (var coord in coordinates)
{
Console.WriteLine("[" + coord.X + ", " + coord.Y + "]");
}
Console.ReadKey();
}
public static IEnumerable<Point> Coordinates(Point start, Point end)
{
var difX = Math.Abs(end.X - start.X + 1);
var difY = Math.Abs(end.Y - start.Y + 1);
var iterations = (difX > difY) ? difX : difY;
for (var i = 0; i < iterations; i++)
{
if (difX > 0)
{
difX--;
}
if (difY > 0)
{
difY--;
}
yield return new Point(end.X - difX, end.Y - difY);
}
}
}
internal struct Point
{
public double X { get; set; }
public double Y { get; set; }
public Point(double x, double y)
{
X = x;
Y = y;
}
}
}
The problem here is if the start point is farther to the origin than the end point this doesn't work.
// Start point (10, 10), end point (5, 3)
// Actual results:
[2, -2]
[3, -1]
[4, 0]
[5, 1]
[5, 2]
[5, 3]
// Desired:
[10, 10]
[9, 9]
[8, 8]
[7, 7]
[6, 6]
[5, 5]
[5, 4]
[5, 3]
// If I reverse start and end points the result is as expected:
[5, 3]
[6, 4]
[7, 5]
[8, 6]
[9, 7]
[10, 8]
[10, 9]
[10, 10]
A simple loop while checking if we reach end point or not:
Code:
public static IEnumerable<Point> Coordinates(Point start, Point end) {
int dx = Math.Sign(end.X - start.X);
int dy = Math.Sign(end.Y - start.Y);
int steps = Math.Max(Math.Abs(end.X - start.X), Math.Abs(end.Y - start.Y)) + 1;
int x = start.X;
int y = start.Y;
for (int i = 1; i <= steps; ++i) {
yield return new Point(x, y);
x = x == end.X ? end.X : x + dx;
y = y == end.Y ? end.Y : y + dy;
}
}
Demo:
Console.WriteLine(string.Join(Environment.NewLine,
Coordinates(new Point(10, 10), new Point(5, 3))));
Console.WriteLine();
Console.WriteLine(string.Join(Environment.NewLine,
Coordinates(new Point(5, 3), new Point(10, 10))));
Outcome:
{X=10,Y=10}
{X=9,Y=9}
{X=8,Y=8}
{X=7,Y=7}
{X=6,Y=6}
{X=5,Y=5}
{X=5,Y=4}
{X=5,Y=3}
{X=5,Y=3}
{X=6,Y=4}
{X=7,Y=5}
{X=8,Y=6}
{X=9,Y=7}
{X=10,Y=8}
{X=10,Y=9}
{X=10,Y=10}
DISCLAIMER: Untested!
This is how I would approach this:
public static IEnumerable<Point> Coordinates(Point start, Point end)
{
double dirX = start.X < end.X ? +1 : -1;
double dirY = start.Y < end.Y ? +1 : -1;
double x = start.X;
double y = start.Y;
do
{
if (!coordsEqual(x, end.X)) x = x+dirX;
if (!coordsEqual(y, end.Y)) x = y+dirY;
yield return new Point(x,y);
}while( !shouldStop(x,y,end) );
}
static bool shouldStop( double x, double y, Point target )
{
// Basically x == end.X && y == end.Y , just considering floating point issues.
return coordsEqual( x, target.X ) && coordsEqual( y, target.Y );
}
static bool coordsEqual( double d1, double d2 )
{
// TODO
}
Mind that I left some work to do. Checking equality on doubles has quite some pitfalls, so I left it up to you to learn about them.
BTW: You seem to only use integer values. Checking equality is much easier if you use int instead of double.
You Math.Abs when working out how much you need to step, which loses the direction of your stepping and all your paths can only thus proceed in a positive direction. Instead keep the stepping as positive or negative:
public static IEnumerable<Point> Coordinates(Point start, Point end)
{
int difX = end.X - start.X;
int difY = end.Y - start.Y;
var iterations = (difX > difY) ? difX : difY;
//reduce the stepping to either +1 or -1 for each
difX = difX/Math.Abs(difX);
difY = difY/Math.Abs(difY);
//start off one behind, because we'll increment in the loop
int newX = start.X - difX;
int newY = start.Y - difY;
//now when you loop, only apply the stepping if you didnt already reach the end
for (var i = 0; i < iterations; i++)
{
//only move if we didn't reach the end
if(newX != end.X)
newX += difX;
if(newY != end.Y)
newY += difY;
yield return new Point(newX, newY);
}
}

C# 2D array interpolation

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.

mandlebrot fractal error in the plotted function

Hello guys i am trying plotting the mandlebrot fractal but the result is very far from it, can you help me to find the why?
Here is the code:
void Button1Click(object sender, EventArgs e)
{
Graphics g = pbx.CreateGraphics();
Pen p = new Pen(Color.Black);
double xmin = -2.0;
double ymin = -1.2;
double xmax = 0;
double ymax = 0;
double x = xmin, y = ymin;
int MAX = 1000;
double stepY = Math.Abs(ymin - ymax)/(pbx.Height);
double stepX = Math.Abs(xmin - xmax)/(pbx.Width);
for(int i = 0; i < pbx.Width; i++)
{
y = ymin;
for(int j = 0; j < pbx.Height; j++)
{
double rez = x;
double imz = y;
int iter = 0;
while(rez * rez + imz * imz <= 4 && iter < MAX)
{
rez = rez * rez - imz * imz + x;
imz = 2 * rez * imz + y;
iter++;
}
if(iter == MAX)
{
p.Color = Color.Black;
g.DrawRectangle(p, i, j, 1, 1);
}
else
{
p.Color = Color.White;
g.DrawRectangle(p, i, j, 1, 1);
}
y += stepY;
}
x += stepX;
}
}
please help me my mind is getting crushed thinking how to get the beautiful mandlebrot set...
and sorry if i committed some mistakes but English is not my speaked language!
You have some irregularities elsewhere. The range you're plotting isn't the entire set, and I would calculate x and y directly for each pixel, rather than using increments (so as to avoid rounding error accumulating).
But it looks to me as though your main error is in the iterative computation. You are modifying the rez variable before you use it in the computation of the new imz value. Your loop should look more like this:
while(rez * rez + imz * imz <= 4 && iter < MAX)
{
double rT = rez * rez - imz * imz + x;
imz = 2 * rez * imz + y;
rez = rT;
iter++;
}
Additionally to Peters answer, you should use a color palette instead of drawing just black and white pixels.
Create a array of colors, like this: (very simple example)
Color[] colors = new Colors[768];
for (int i=0; i<256; i++) {
colors[i ]=Color.FromArgb( i, 0, 0);
colors[i+256]=Color.FromArgb(255-i, i, 0);
colors[i+512]=Color.FromArgb(0 , 255-i, i);
}
Then use the iter value to pull a color and draw it:
int index=(int)((double)iter/MAX*767);
p.Color c = colors[index];
g.DrawRectangle(p, i, j, 1, 1);
Replace the entire if (iter == MAX) ... else ... statement with this last step.

OutOfMemoryException For Maze Solver of Large Dimensions

The Program Works for arrays upto 20x20 But for anything larger it throws an OutOfMemoryException.
Below is the code:
public static Point GetFinalPath(int x, int y) {
queue.Enqueue(new Point(x,y, null));
while(queue.Count>0) {
Point p = queue.Dequeue();
if (arr[p.x,p.y] == 9) {
Console.WriteLine("Found Destination");
return p;
}
if(IsOpen(p.x+1,p.y)) {
arr[p.x,p.y] = 1;
queue.Enqueue(new Point(p.x+1,p.y, p));
}
//similarly for the other directions
}
return null;
}
public int[,] SolutionMaze()
{
Point p = GetFinalPath(0, 0);
while (p.getParent() != null)
{
solvedarray[p.x, p.y] = 9;
p = p.getParent();
}
return solvedarray;
}
ok people here is the rest of the code
public static Queue<Point> queue=new Queue<Point>();
public static bool IsOpen(int x, int y)
{
//BOUND CHECKING
if ((x >= 0 && x < XMAX) && (y >= 0 && y < YMAX) && (arr[x,y] == 0 || arr[x,y] == 9))
{
return true;
}
return false;
}
public class Point
{
public int x;
public int y;
Point parent;
public Point(int x, int y, Point parent)
{
this.x = x;
this.y = y;
this.parent = parent;
}
public Point getParent()
{
return this.parent;
}
}
Assumes start to be 0,0 and final destination is set as 9 at the constructor.
Help me implement this for an array of size 500x500
Well, looking at your code I found one problem. You perform the wrong check. You should check if your point is already added to a queue. What do you do now? We'll, you are just marking processed cell as not open. It's easy to see that you can add to queue same node twice.
Let's follow my example:
1 | . .
0 | ! .
--+----
yx| 0 1
Queue: point (0,0)
We are starting at point(0,0). At this moment, we are adding points (0, 1) and (1,0) to our queue and mark point(0,0) as processed
1 | . .
0 | X !
--+----
yx| 0 1
Queue: point (0,1), point (1,0)
Now we dequeue point(0,1), marking it processed and adding point(1,1) to queue.
1 | ! .
0 | X X
--+----
yx| 0 1
Queue: point (1,0), point(1,1)
Now we dequeue point(1,0), marking it as processed and adding point(1,1) to queue:
1 | X !
0 | X X
--+----
yx| 0 1
Queue: point (1,1), point (1,1)
And now we have same point twice in a queue. And that is not your last problem. Your points have a reference to all it parents, so your previous points (doubled too) can't be processed with Garbage Collector.
Okay i found an answer to the OutOfMemory. Now the code works even for 500x500 matrix
As it turns out i just implemented a node list which keeps track of added nodes in queue using y*MAX_X_LENGTH + x formula
public static Queue<Point> queue=new Queue<Point>();
public SolveMaze(int[,] array,int staX,int staY,int finX,int finY)
{
//sets Destination as 9
arr = array;
XMAX = array.GetLength(0);
YMAX = array.GetLength(1);
finishY = finX; finishX = finY; startY = staX; startX = staY;
solvedarray = new int[XMAX, YMAX];
}
public static List<int> nodelist=new List<int>();
public void AddPointToQueueIfOpenAndNotAlreadyPresent(Point p,int direction)
{
if (nodelist.Contains(XMAX * p.y + p.x))
return;
else
{
switch(direction){
case 1:
//north
if (IsOpen(p.x, p.y - 1))
{
arr[p.x, p.y] = 1;
queue.Enqueue(new Point(p.x, p.y - 1, p));
nodelist.Add(XMAX * (p.y - 1) + p.x);
}
break;
case 0:
//east
if (IsOpen(p.x + 1, p.y))
{
arr[p.x, p.y] = 1;
queue.Enqueue(new Point(p.x + 1, p.y, p));
nodelist.Add(XMAX * (p.y) + p.x + 1);
}
break;
case 3:
//south
if (IsOpen(p.x, p.y + 1))
{
arr[p.x, p.y] = 1;
queue.Enqueue(new Point(p.x, p.y +1, p));
nodelist.Add(XMAX * (p.y + 1) + p.x);
}
break;
case 2:
//west
if (IsOpen(p.x - 1, p.y))
{
arr[p.x, p.y] = 1;
queue.Enqueue(new Point(p.x - 1, p.y, p));
nodelist.Add(XMAX * (p.y) + p.x-1);
}
break; }
}
}
public Point GetFinalPath(int x, int y) {
if (arr[finishX, finishY] == 0)
arr[finishX, finishY] = 9;
else
return null;
queue.Enqueue(new Point(x, y, null));
nodelist.Add(XMAX * y + x);
while(queue.Count>0) {
Point p = queue.Dequeue();
nodelist.Remove(p.y * XMAX + p.x);
if (arr[p.x,p.y] == 9) {
Console.WriteLine("Exit is reached!");
return p;
}
for (int i = 0; i < 4; i++)
{
AddPointToQueueIfOpenAndNotAlreadyPresent(p, i);
}
}
return null;
}
public static bool IsOpen(int x, int y)
{
//BOUND CHECKING
if ((x >= 0 && x < XMAX) && (y >= 0 && y < YMAX) && (arr[x,y] == 0 || arr[x,y] == 9))
{
return true;
}
return false;
}
public int[,] SolutionMaze()
{
Point p = GetFinalPath(startX, startY);
if(p!=null)
while (p.getParent() != null)
{
solvedarray[p.x, p.y] = 9;
p = p.getParent();
}
return solvedarray;
}
}
public class Point
{
public int x;
public int y;
Point parent;
public Point(int x, int y, Point parent)
{
this.x = x;
this.y = y;
this.parent = parent;
}
public Point getParent()
{
return this.parent;
}
}

Categories