TweetFollow Us on Twitter

Jul 99 Challenge

Volume Number: 15 (1999)
Issue Number: 7
Column Tag: Programmer's Challenge

by Bob Boonstra, Westford, MA

C-to-HTML

This month, your Challenge is simple enough: generate a little HTML. Not just any HTML, of course, but HTML that displays a C or C++ program the way it looks in your Metrowerks CodeWarrior editor window. The prototype for the code you should write is:

#if defined (__cplusplus)
extern "C" {
#endif

typedef struct Settings {
	unsigned long commentColor;	/*00RRGGBB*/
	unsigned long keywordColor;	/*00RRGGBB*/
	unsigned long stringColor;	/*00RRGGBB*/
	char fontName[32];		/* font to use for display */
	unsigned long fontSize;	/* size of font to use */
	unsigned long tabSize;	/* number of spaces to use for tabs */
} Settings;

long /* output length */ CtoHTML(
	const char *inputText,	/* text to convert */
	char *outputHTML,		/* converted text */
	const Settings displaySettings	/* display parameters */
);

#if defined (__cplusplus)
}
#endif

A syntactically correct C or C++ program will be provided to you as inputText. You should convert that program to HTML so that, when displayed in the current Netscape browser (4.6 as of this writing), the code will appear as the input does when opened in CodeWarrior. The output HTML should be stored in (surprise) outputHTML, and the number of characters generated should be returned by your CtoHTML routine. Your CodeWarrior display preferences are provided in displaySettings: the colors to be used for comments, keywords, and strings, the name and size of the font to be used. The tabSize parameter should be used to convert tab characters to the appropriate number of nonbreaking spaces, so that the HTML appears correct no matter what tab setting is used in CodeWarrior.

The winner will be the solution that correctly converts C into HTML in the minimum amount of execution time. Solutions within 1% of one another in total execution time will be ranked by code size and elegance.

This will be a native PowerPC Challenge, using the latest CodeWarrior environment. Solutions may be coded in C, C++, or Pascal.

This Challenge was suggested by Dennis Jones, who earns 2 Challenge points for the idea.

Three Months Ago Winner

Congratulations to Sebastian Maurer for submitting the winning entry to the April Shortest Network Challenge. This Challenge required readers to find a network of line segments connecting a specified set of nodes, minimizing both the total length of the line segments and the execution time used to create the network. Solutions were allowed to create intermediate "Steiner" nodes to reduce network length, although only one of the five solutions submitted took advantage of that option.

Sebastian's entry calculates the minimum spanning tree as a subset of the edges in a Delaunay triangulation. A concept that was also discussed by participants in the March Find A Pass Challenge, a Delaunay triangulation of a set of points in a plane has the property that the circles circumscribing the triangles do not contain any points in the set. Sebastian's solution calculates the Delaunay triangles, sorts the segments in those triangles from shortest to longest, and selects a subset of N-1 segments connecting the N points, avoiding the creation of any loops in the process.

In one of the test problems, 2000 nodes were randomly distributed within eight square regions roughly distributed in a octagonal pattern. A network generated by Sebastian's entry to this test problem is depicted below.


Network generated by Sebastian Maurer's solution

Sebastian's solution won by creating a shorter network than the other solutions. The second place solution submitted by Ernst Munter was the only entry that inserted intermediate nodes into the network. While faster, it created longer networks. Ernst decided that calculating the minimum spanning tree would be too costly, and instead calculated an approximation to the minimum spanning tree in sections. Ernst then added intermediate points until the angles formed by the segments meet a heuristic criterion. The network produced by Ernst's solution to the problem described earlier is shown in the next figure.


Network generated by Ernst Munter's solution

Note that this network contains the loops avoided by Sebastian's solution. The extra segments making up these loops account for the fact that the generated network is longer, despite the inclusion of Steiner points.

The evaluation was based on performance against 5 test cases, with an average of 2000 points per test case. The table below lists the total length of the generated networks, the number of intermediate nodes inserted into the networks, the total number of segments in the networks, the total execution time, and the overall score, as well as the code size, data size, and programming language for each of the solutions submitted. As usual, the number in parentheses after the entrant's name is the total number of Challenge points earned in all Challenges prior to this one.

Name (size) Length Intermed # of Nodes Time Connect (msec) Score Code Data Lang
Sebastian Maurer (40) 17795 0 9995 696 18042 9536 320 C
Ernst Munter (437) 18361 3869 13864 648 18598 8588 8152 C++
Randy Boring (103) 18598 0 9995 58236 38374 2572 179 C
Willeke Rieken (47) 18589 0 9995 54462 38686 6640 48 C++
Andrew Downs 27439 0 9995 522169 313867 872 32 C

Top Contestants

Listed here are the Top Contestants for the Programmer's Challenge, including everyone who has accumulated 10 or more points during the past two years. The numbers below include points awarded over the 24 most recent contests, including points earned by this month's entrants.

Rank Name Points
1. Munter, Ernst 205
2. Saxton, Tom 99
3. Boring, Randy 73
4. Maurer, Sebastian 60
5. Rieken, Willeke 51
6. Heithcock, JG 37
7. Lewis, Peter 31
8. Nicolle, Ludovic 27
9. Brown, Pat 20
10. Day, Mark 20
11. Hostetter, Mat 20
12. Mallett, Jeff 20
13. Murphy, ACC 14
14. Jones, Dennis 12
15. Hewett, Kevin 10
16. Selengut, Jared 10
17. Smith, Brad 10
18. Varilly, Patrick 10
19. Webb, Russ 10

There are three ways to earn points: (1) scoring in the top 5 of any Challenge, (2) being the first person to find a bug in a published winning solution or, (3) being the first person to suggest a Challenge that I use. The points you can win are:

1st place 20 points
2nd place 10 points
3rd place 7 points
4th place 4 points
5th place 2 points
finding bug 2 points
suggesting Challenge 2 points

Here is Sebastian Maurer's winning Shortest Network solution:

/*
Since the minimum spanning tree (MST) is never that much longer than the Steiner tree, and since the MST is so much easier to calculate, I wont bother searching for Steiner points.
My solution works in three stages: first, construct a list of segments. Second, quicksort them from shortest to longest. Finally, connect the shortest segments together without forming loops.
The MST is a subset of the edges in a Delauney triangulation - it is good to use the triangulation's O(N) edges rather than to have to sort all possible O(N^2) edges.  Finding the Delauney graph makes for the bulk of the code. For comparison, I left the code for the exhaustive listing of edges at the end of the file.  Just replace the call to DelauneySegments() by AllSegments() in ShortestNetwork() to see the difference.
The Delauney triangulation is done following the algorithm described in the book "Computational Geometry: Algorithms and Applications" by M. de Berg et al.
The memory requirement is about 500 bytes per node in addition to what the test code needs. For N points, 9 N + 1 triangles are needed at the most. Each triangle
requires 40 bytes. I need 3 N segments (16 bytes each), and 2 N longs for a total of 416 bytes. The largest sample I tried was 160000 points with an 80 Mb allocation. It took a minute and a half on a 233 MHz G3.
I didn't have much time to work on robustness. There may still be ways to provide a set of nodes that will cause my program to fail.
*/


#include "ShortestNetwork.h"


typedef struct Triangle {
	Node *a, *b, *c;
	// keep pointers to neighbors sharing an edge
	struct Triangle *ab, *bc, *ca;
	// and keep pointers to up to three children
	struct Triangle *child1, *child2, *child3;
	// mark triangles seen in tree traversal
	Boolean visited;
} Triangle;


typedef struct Segment {
	Connection c;
	double distSq;
} Segment;



Prototypes


long DelauneySegments(long numNodes, Node nodes[],
					  Segment *segments[],
					  Connection connections[],
					  long *numDuplicates);			  
void Quicksort(Segment segs[], long first, long last);
void BuildSpanningTree(long numNodes, Segment segs[],
					   Connection connections[],
					   long numDuplicates);


ShortestNetwork

long /* numConnections */ ShortestNetwork(
	long numInitialNodes,	/* number of nodes to connect */
	long *numIntermediateNodes, /* number of nodes added by 																	ShortestNetwork */
	Node nodes[], 
		/* Nodes 0..numInitialNodes-1 are initialized on entry. */
		/* Nodes numInitialNodes..numInitialNodes+*numIntermediateNodes 				added by ShortestNetwork */
	Connection connections[],	/* connections between nodes */
	long maxNodes,
	long maxConnections
) {
	long numSegments;
	Segment *segs;
	long numDuplicates;


	if (maxConnections<numInitialNodes) return -1;
	if (maxNodes<numInitialNodes+1) return -1;

	numSegments =
		DelauneySegments(numInitialNodes, nodes, &segs,
						 connections, &numDuplicates);
	Quicksort(segs, 0, numSegments - 1 - numDuplicates);	
	BuildSpanningTree(numInitialNodes, segs, connections,
					  numDuplicates);
	DisposePtr((char*)segs);
	*numIntermediateNodes = 0;


	// since I didn't add any nodes...
	return numInitialNodes - 1;
}

sameLabel

////////
// Given an ordered list or candidate segments,
// BuildSpanningTree fills the array with the
// (numNodes - 1) connections necessary to build
// a spanning tree. If the array of segments contains
// all the necessary edges, then the spanning tree is
// minimal.
////////
// To figure out whether to labels are equivalent,
// we iterate down the equivalence array for both
// labels until the equivalent labels are equal to
// themselves. Then we can compare.
static Boolean sameLabel(long equiv[],
						 long label1, long label2)
{
	while (equiv[label1] != label1)
		label1 = equiv[label1];
	while (equiv[label2] != label2)
		label2 = equiv[label2];
	return label1 == label2;
}


isConnected

// Two nodes can only be connected if they were
// both already labeled with equivalent labels
static Boolean isConnected(long label[], long equiv[],
						   long node1, long node2)
{
	return (label[node1] > 0) && (label[node2] > 0) &&
			sameLabel(equiv, label[node1], label[node2]);
}



BuildSpanningTree

void BuildSpanningTree(long numNodes, Segment segs[],
					   Connection connections[],
					   long numDuplicates)
// segs should be sorted from shortest to longest
// We pick (numNodes - 1) segments, starting from shortest,
// and make sure to never make a closed loop
{
	long i, j, nextLabel;
	long *label =
		(long*)NewPtr((Size)(numNodes * sizeof(long)));
	long *equiv =
		(long*)NewPtr((Size)(numNodes * sizeof(long)));
	if ((label == NULL) || (equiv == NULL))
		DebugStr("\pNot enough mem in BuildSpanningTree");
	for(i = 0; i < numNodes; i++) {
		label[i] = 0;
		equiv[i] = i;
	}
	nextLabel = 1;
	j = -1;
	for(i = numDuplicates; i < numNodes - 1; i++) {
		long node1, node2;
		do {
			j += 1;
			node1 = segs[j].c.index1;
			node2 = segs[j].c.index2;
		} while (isConnected(label, equiv, node1, node2));
		connections[i].index1 = node1;
		connections[i].index2 = node2;
		if (label[node1] == 0) {
			if (label[node2] == 0) {
				label[node1] = nextLabel;
				label[node2] = nextLabel;
				nextLabel += 1;
			} else {
				label[node1] = label[node2];
			}
		} else {
			if (label[node2] == 0) {
				label[node2] = label[node1];
			} else {
				long lab1 = label[node1];
				long lab2 = label[node2];
				if (lab1 > lab2) {
					while (equiv[lab1] != lab1)
						lab1 = equiv[lab1];
					equiv[lab1] = lab2;
				} else {
					while (equiv[lab2] != lab2)
						lab2 = equiv[lab2];
					equiv[lab2] = lab1;
				}
			}
		}
	}

		
	DisposePtr((char*)label);
	DisposePtr((char*)equiv);
}

SwapSegments

////////
// quicksort the array of segments
// sorting records rather than pointers
// is costly, but still fast compared
// to the Delauney graph calculation
////////
static inline void SwapSegments(Segment segs[],
								long i, long j)
{	
	Segment temp;
	temp.c.index1 = segs[i].c.index1;
	temp.c.index2 = segs[i].c.index2;
	temp.distSq = segs[i].distSq;
	segs[i].c.index1 = segs[j].c.index1;
	segs[i].c.index2 = segs[j].c.index2;
	segs[i].distSq = segs[j].distSq;
	segs[j].c.index1 = temp.c.index1;
	segs[j].c.index2 = temp.c.index2;
	segs[j].distSq = temp.distSq;
}

Quicksort

void Quicksort(Segment segs[], long first, long last)
{
	long left, right;
	double dividingValue;
  	left = first;
  	right = last;
  	dividingValue = segs[(first + last) / 2].distSq;
  	do { // until right < left
  		while (segs[left].distSq < dividingValue)
  			left += 1;
  		while (segs[right].distSq > dividingValue)
  			right -= 1;
  		if (left <= right) {
  			SwapSegments(segs, left, right);
  			left += 1;
  			right -= 1;
  		}
  	} while (right >= left);
  	if (right > first)
  		Quicksort(segs, first, right);
  	if (left < last)
  		Quicksort(segs, left, last);
}


det

/////
// Utility functions for the analytic geometry we need
/////


// In order to figure out whether p is to the left of the
// directed line formed by the points a and b, check if
// the following determinant is positive
//
// |  a.x  a.y  1 |
// |  b.x  b.y  1 | > 0
// |  p.x  p.y  1 |
//
static double det(Node *a, Node *b, Node *c)
{
	// neat - the determinant above can be
	// calculated with only two multiplications
	return (b->y - a->y) * (a->x - c->x) +
		   (b->x - a->x) * (c->y - a->y);
}

isInTriangle

// The vertices a, b and c of my triangles are always in
// counter clock wise order. Then a point p is inside the
// triangle only if it is to the left of the directed lines
// ab, bc and ca.
// By inside I mean *strictly* inside (not on an edge!)
static Boolean isInTriangle(Node *p, Triangle *triangle)
{
	return (det(triangle->a, triangle->b, p) > 0) &&
		   (det(triangle->b, triangle->c, p) > 0) &&
		   (det(triangle->c, triangle->a, p) > 0);
}

isOnTriangle

// By "on" I mean inside including the edges. I use
// epsilon to allow for floating point rouding problems
static Boolean isOnTriangle(Node *p, Triangle *triangle,
							double negEpsilon)
{
	return (det(triangle->a, triangle->b, p) > negEpsilon)
		&& (det(triangle->b, triangle->c, p) > negEpsilon)
		&& (det(triangle->c, triangle->a, p) > negEpsilon);
}

isInsideCircumscribedCircle

// In order to figure out whether p is inside the
// circumscribed circle of the triangle abc check
// whether the following determinant is positive
//
// |  a.x  a.y  a.x^2 + a.y^2  1 |
// |  b.x  b.y  b.x^2 + b.y^2  1 |  >  0
// |  c.x  c.y  c.x^2 + c.y^2  1 |
// |  p.x  p.y  p.x^2 + p.y^2  1 |
static Boolean isInsideCircumscribedCircle(
					Node *a, Node *b, Node *c, Node *p)
{
	return (a->x * a->x + a->y * a->y) * det(b, c, p)
		 - (b->x * b->x + b->y * b->y) * det(a, c, p)
		 + (c->x * c->x + c->y * c->y) * det(a, b, p)
		 - (p->x * p->x + p->y * p->y) * det(a, b, c) > 0;
}



MakeNewTriangle

/////
// Procedures for Delauney graph calculation
/////
// Triangles always have vertices in CCW order
// (so that det(a, b, c) is positive)
static void MakeNewTriangle(Triangle *t,
					 Node *a, Node *b, Node *c,
					 Triangle *ab, Triangle *bc,
					 Triangle *ca)
{
	t->a = a;
	t->b = b;
	t->c = c;
	t->ab = ab;
	t->bc = bc;
	t->ca = ca;
	t->child1 = NULL;
	t->child2 = NULL;
	t->child3 = NULL;	
	t->visited = false;
	if (det(a, b, c) <= 0)
		DebugStr("\pIllegal triangle created");
}



FindCommonEdge

// Given two triangles with a common edge, return
// pointers to each of the four vertices involved
// (o1, c1, c2 and o2 are in CCW order. o1 and o2
// are on the outside, and c1 and c2 are common
// to both triangles), as well as pointers
// to the neighboring triangles
static void FindCommonEdge(Triangle *t1, Triangle *t2,
						   Node **o1, Node **c1,
						   Node **c2, Node **o2,
						   Triangle **o1c1, Triangle **c2o1,
						   Triangle **o2c2, Triangle **c1o2)
{
	if ((t1->a != t2->a) && (t1->a != t2->b) &&
		(t1->a != t2->c))
	{
		*o1 = t1->a;
		*c1 = t1->b;
		*c2 = t1->c;
		*o1c1 = t1->ab;
		*c2o1 = t1->ca;
	} else if ((t1->b != t2->a) && (t1->b != t2->b) &&
			   (t1->b != t2->c))
	{
		*o1 = t1->b;
		*c1 = t1->c;
		*c2 = t1->a;
		*o1c1 = t1->bc;
		*c2o1 = t1->ab;
	} else if ((t1->c != t2->a) && (t1->c != t2->b) &&
			   (t1->c != t2->c))
	{
		*o1 = t1->c;
		*c1 = t1->a;
		*c2 = t1->b;
		*o1c1 = t1->ca;
		*c2o1 = t1->bc;
	} else {
		DebugStr("\pt1 and t2 are identical");
		return;
	}

	

	if ((t2->a != t1->a) && (t2->a != t1->b) &&
		(t2->a != t1->c))
	{
		*o2 = t2->a;
		if(*c2 != t2->b) DebugStr("\pProblem");
		if(*c1 != t2->c) DebugStr("\pProblem");
		*o2c2 = t2->ab;
		*c1o2 = t2->ca;
	} else if ((t2->b != t1->a) && (t2->b != t1->b) &&
			   (t2->b != t1->c))
	{
		*o2 = t2->b;
		if(*c2 != t2->c) DebugStr("\pProblem");
		if(*c1 != t2->a) DebugStr("\pProblem");
		*o2c2 = t2->bc;
		*c1o2 = t2->ab;
	} else if ((t2->c != t1->a) && (t2->c != t1->b) &&
			   (t2->c != t1->c))
	{
		*o2 = t2->c;
		if(*c2 != t2->a) DebugStr("\pProblem");
		if(*c1 != t2->b) DebugStr("\pProblem");
		*o2c2 = t2->ca;
		*c1o2 = t2->bc;
	}
	else DebugStr("\pA very serious problem");
}



DivideTriangleInto3

// Given a point p inside a triangle t,
// create the three new children of triangle t
// and update all the neighbors' pointers
static void DivideTriangleInto3(Triangle *t, Node *p)
{
 	MakeNewTriangle(t->child1, p, t->a, t->b,
 					t->child3, t->ab, t->child2);
	if (t->ab != NULL) {
		if (t->ab->ab == t) t->ab->ab = t->child1;
		if (t->ab->bc == t) t->ab->bc = t->child1;
		if (t->ab->ca == t) t->ab->ca = t->child1;
	}

	

	MakeNewTriangle(t->child2, p, t->b, t->c,
					t->child1, t->bc, t->child3);	
	if (t->bc != NULL) {
		if (t->bc->ab == t) t->bc->ab = t->child2;
		if (t->bc->bc == t) t->bc->bc = t->child2;
		if (t->bc->ca == t) t->bc->ca = t->child2;
	}


	MakeNewTriangle(t->child3, p, t->c, t->a,
					t->child2, t->ca, t->child1);
	if (t->ca != NULL) {
		if (t->ca->ab == t) t->ca->ab = t->child3;
		if (t->ca->bc == t) t->ca->bc = t->child3;
		if (t->ca->ca == t) t->ca->ca = t->child3;
	}
}


Divide2TrianglesInto2

// Given a point p on the edge between two triangles,
// create four new triangles and update all the
// edges, pointers, etc...
// The two child1 triangles will have a common edge
// and the two child2 will have a common edge
static void Divide2TrianglesInto2(
				Triangle *t1, Triangle *t2, Node *p)
{
	// Vertices
	Node *o1, *c1, *o2, *c2;
	// pointers to triangles on outside of quadrilateral
	Triangle *o2c2, *c2o1, *o1c1, *c1o2;
	FindCommonEdge(t1, t2, &o1, &c1, &c2, &o2,
				   &o1c1, &c2o1, &o2c2, &c1o2);
	MakeNewTriangle(t1->child1, p, c2, o1,
					t2->child1, c2o1, t1->child2);
	if (c2o1 != NULL) {
		if (c2o1->ab == t1) c2o1->ab = t1->child1;
		if (c2o1->bc == t1) c2o1->bc = t1->child1;
		if (c2o1->ca == t1) c2o1->ca = t1->child1;
	}
	MakeNewTriangle(t1->child2, p, o1, c1,
					t1->child1, o1c1, t2->child2);
	if (o1c1 != NULL) {
		if (o1c1->ab == t1) o1c1->ab = t1->child2;
		if (o1c1->bc == t1) o1c1->bc = t1->child2;
		if (o1c1->ca == t1) o1c1->ca = t1->child2;
	}
	MakeNewTriangle(t2->child1, p, o2, c2,
					t2->child2, o2c2, t1->child1);
	if (o2c2 != NULL) {
		if (o2c2->ab == t2) o2c2->ab = t2->child1;
		if (o2c2->bc == t2) o2c2->bc = t2->child1;
		if (o2c2->ca == t2) o2c2->ca = t2->child1;
	}
	MakeNewTriangle(t2->child2, p, c1, o2,
					t1->child2, c1o2, t2->child1);
	if (c1o2 != NULL) {
		if (c1o2->ab == t2) c1o2->ab = t2->child2;
		if (c1o2->bc == t2) c1o2->bc = t2->child2;
		if (c1o2->ca == t2) c1o2->ca = t2->child2;
	}
}



isSpecial

// Check whether point p is one of the fake
// points I added for convenience
static inline Boolean isSpecial(Node *p, double max)
{
	return (p->x > max) || (p->y > max) ||
		   (p->x < -max) || (p->y < -max);
}



intersects

// Two segments intersect if the endpoints of one
// lie on opposite sides of the line formed by the
// other two points, and vice-versa
static Boolean intersects(Node *a1, Node *a2,
						  Node *b1, Node *b2)
{
	double a1a2b1 = det(a1, a2, b1);
	double a1a2b2 = det(a1, a2, b2);
	double b1b2a1 = det(b1, b2, a1);
	double b1b2a2 = det(b1, b2, a2);
	return (((a1a2b1 > 0) && (a1a2b2 < 0)) ||
			((a1a2b1 < 0) && (a1a2b2 > 0))) &&
		   (((b1b2a1 > 0) && (b1b2a2 < 0)) ||
			((b1b2a1 < 0) && (b1b2a2 > 0)));
}



LegalizeEdge

// LegalizeEdge flips the common edge
// between two triangles if the initial edge can not
// be part of the Delauney graph
static void LegalizeEdge(Triangle *t1, Triangle *t2,
				Triangle triangles[], int *free, double max)
{
	// t1 and t2 are two triangles with a common edge
	// t1 has all the edges legalized from the caller
	// t2 will need to be legalized recursively if the
	// edge shared with t1 is flipped
	// Vertices in CCW order
	Node *o1, *c1, *o2, *c2;
	// Triangles on outside of quadrilateral
	Triangle *o2c2, *c2o1, *o1c1, *c1o2;
	Boolean specialCase, generalCase;
	Boolean c1Special, c2Special, o2Special, o1Special;
	// If there is no neighboring triangle, the edge has
	// to be legal. This happens if the edge c1c2 is
	// formed by two special points
	if ((t1 == NULL) || (t2 == NULL))
		return;
	FindCommonEdge(t1, t2, &o1, &c1, &c2, &o2,
				   &o1c1, &c2o1, &o2c2, &c1o2);
	c1Special = isSpecial(c1, max);
	c2Special = isSpecial(c2, max);
	o1Special = isSpecial(o1, max);
	o2Special = isSpecial(o2, max);
	// The two common vertices can't be special
	// since all added points are inside the
	// triangle formed by the three special points 
	if (c1Special && c2Special)
		DebugStr("\pBoth common vertices are special");
	// If both opposite vertices are special
	// (this can happen if the point falls on a
	// preexisting edge) we don't flip the edge
	if (o1Special && o2Special)
		return;
	// If one of the opposite vertices is special, we
	// don't flip the edge between the two common points 
	if (o2Special || o1Special)
		return;
	// If exactly one of the common vertices is special,
	// we flip the edge if the union of both triangles
	// is concave - otherwise we won't get a proper
	// triangle after the flip
	specialCase = (c1Special || c2Special) &&
				  (intersects(o1, o2, c1, c2));
	// Finally the general case when none of the points
	// is special.
	generalCase =
		!(c1Special || c2Special ||
		  o2Special || o1Special) &&
		isInsideCircumscribedCircle(o1, c1, c2, o2);
	if (specialCase || generalCase) {		
		// Create new triangles
		Triangle *newT1, *newT2;
		newT1 = &(triangles[*free]);
		*free += 1;
		newT2 = &(triangles[*free]);
		*free += 1;
		// Assign new children
		t1->child1 = newT1;
		t1->child2 = newT2;
		t2->child1 = newT1;
		t2->child2 = newT2;
		MakeNewTriangle(newT1, o1, o2, c2,
						newT2, o2c2, c2o1);
		MakeNewTriangle(newT2, o1, c1, o2,
						o1c1, c1o2, newT1);
		// Update pointers from neighbors
		if (o2c2 != NULL) {
			if (o2c2->ab == t2) o2c2->ab = newT1;
			if (o2c2->bc == t2) o2c2->bc = newT1;
			if (o2c2->ca == t2) o2c2->ca = newT1;
		}
		if (c2o1 != NULL) {
			if (c2o1->ab == t1) c2o1->ab = newT1;
			if (c2o1->bc == t1) c2o1->bc = newT1;
			if (c2o1->ca == t1) c2o1->ca = newT1;
		}
		if (o1c1 != NULL) {
			if (o1c1->ab == t1) o1c1->ab = newT2;
			if (o1c1->bc == t1) o1c1->bc = newT2;
			if (o1c1->ca == t1) o1c1->ca = newT2;
		}
		if (c1o2 != NULL) {
			if (c1o2->ab == t2) c1o2->ab = newT2;
			if (c1o2->bc == t2) c1o2->bc = newT2;
			if (c1o2->ca == t2) c1o2->ca = newT2;
		}
		// and recursively legalize the new edges on
		// the second new triangle
		LegalizeEdge(newT1, o2c2, triangles, free, max);
		LegalizeEdge(newT2, c1o2, triangles, free, max);
	}
}



isLeaf

// return true if the given triangle is at the
// end of the acyclic directed graph and has
// no more children
static inline Boolean isLeaf(Triangle *t)
{
	return ((t->child1 == NULL) &&
			(t->child2 == NULL) &&
			(t->child3 == NULL));
}



FindTriangle

///////
// Recursively find the triangle that point p is on
// (including the edge).
///////
static Triangle* FindTriangle(Node *p, Triangle *triangle,
							  double negEpsilon)
{
	if (isLeaf(triangle)) return triangle;
	if ((triangle->child1 != NULL) &&
		isOnTriangle(p, triangle->child1, negEpsilon))
			return FindTriangle(p, triangle->child1,
								negEpsilon);
	if ((triangle->child2 != NULL) &&
		isOnTriangle(p, triangle->child2, negEpsilon))
			return FindTriangle(p, triangle->child2,
								negEpsilon);
	if ((triangle->child3 != NULL) &&
		isOnTriangle(p, triangle->child3, negEpsilon))
			return FindTriangle(p, triangle->child3,
								negEpsilon);
	DebugStr("\pProblem in FindTriangle");
	return NULL;
}



FindTheOtherTriangle

// When p is on the edge of a triangle, this function
// returns the triangle that shares this edge
// If p lies on more than edge (i.e. on a vertex),
// then I return NULL
static Triangle* FindTheOtherTriangle(
					Node *p, Triangle *triangle,
					double epsilon)
{
	double detABP = det(triangle->a, triangle->b, p);
	double detBCP = det(triangle->b, triangle->c, p);
	double detCAP = det(triangle->c, triangle->a, p);
	Boolean detABPis0 = (detABP < epsilon) &&
						(detABP > - epsilon);
	Boolean detBCPis0 = (detBCP < epsilon) &&
						(detBCP > - epsilon);
	Boolean detCAPis0 = (detCAP < epsilon) &&
						(detCAP > - epsilon);
	if (detABPis0 && !detBCPis0 && !detCAPis0)
		return triangle->ab;
	if (!detABPis0 && detBCPis0 && !detCAPis0)
		return triangle->bc;
	if (!detABPis0 && !detBCPis0 && detCAPis0)
		return triangle->ca;
	if (detABPis0 || detBCPis0 || detCAPis0)
		return NULL;
		// indicate that p lies on two edges at once
	// p doesn't lie on any edge - we should
	// not have been called in this case
	DebugStr("\pProblem FindTheOtherTriangle");
	return NULL;
}



FindMultipleVertex

// If FindTheOtherTriangle returned NULL, then
// I want to find the vertex that was so close to p
static Node* FindMultipleVertex(Node *p, Triangle *t,
								double epsilon)
{
	double dxa = p->x - t->a->x;
	double dya = p->y - t->a->y;
	double dxb = p->x - t->b->x;
	double dyb = p->y - t->b->y;
	double dxc = p->x - t->c->x;
	double dyc = p->y - t->c->y;
	if ((dxa < epsilon) && (dxa > - epsilon))
		return t->a;
	else if ((dxb < epsilon) && (dxb > - epsilon))
		return t->b;
	else if ((dxc < epsilon) && (dxc > - epsilon))
		return t->c;
	else {
		// We should not have been called
		// if there is no neighboring point!
		// DebugStr("\pProblem in FindMultipleVertex");
		// return NULL;
		// but to be safe I'll just return anything :-)
		return t->a;
	}
}


addPointInsideTriangle

static void addPointInsideTriangle(Node *p, Triangle *t,
		Triangle *triangles, int *free, double max)
{	
	// Now we create the three new triangles
	t->child1 = &(triangles[(*free)++]);
	t->child2 = &(triangles[(*free)++]);
	t->child3 = &(triangles[(*free)++]);
	DivideTriangleInto3(t, p);		
	// and make sure the added edges are part of
	// a real Delauney triangulation
	LegalizeEdge(t->child1, t->ab, triangles, free, max);
	LegalizeEdge(t->child2, t->bc, triangles, free, max);
 	LegalizeEdge(t->child3, t->ca, triangles, free, max);
}



ExtractSegments

///////
// The final step in DelauneySegments is to traverse
// the triangle "tree" to build a list segments. This
// requires that all the nodes have the visited flag
// set to false. (Note that the tree is not really a
// tree, it's actually an "acyclic directed graph". The
// tree is no longer a tree after an edge flip).
///////
static void ExtractSegments(
	long *numSegments, Segment segments[],
	Triangle* mother, Node nodes[], double max)
{
	if (mother != NULL) {
		if (!(mother->visited))
		{
			mother->visited = true;
			if (isLeaf(mother))
			{
				double dx, dy;
				if (!mother->ab->visited &&
					!isSpecial(mother->a, max) &&
					!isSpecial(mother->b, max))
				{
					segments[*numSegments].c.index1 =
						mother->a - &nodes[0];
					segments[*numSegments].c.index2 =
						mother->b - &nodes[0];
					dx = mother->a->x - mother->b->x;
					dy = mother->a->y - mother->b->y;
					segments[*numSegments].distSq =
						dx * dx + dy * dy;
					*numSegments += 1;
				}
				if (!mother->bc->visited &&
					!isSpecial(mother->b, max) &&
					!isSpecial(mother->c, max))
				{
					segments[*numSegments].c.index1 =
						mother->b - &nodes[0];
					segments[*numSegments].c.index2 =
						mother->c - &nodes[0];
					dx = mother->b->x - mother->c->x;
					dy = mother->b->y - mother->c->y;
					segments[*numSegments].distSq =
						dx * dx + dy * dy;
					*numSegments += 1;
				}
				if (!mother->ca->visited &&
					!isSpecial(mother->c, max) &&
					!isSpecial(mother->a, max))
				{
					segments[*numSegments].c.index1 =
						mother->c - &nodes[0];
					segments[*numSegments].c.index2 =
						mother->a - &nodes[0];
					dx = mother->c->x - mother->a->x;
					dy = mother->c->y - mother->a->y;
					segments[*numSegments].distSq =
						dx * dx + dy * dy;
					*numSegments += 1;
				}
			}
			else
			{
				ExtractSegments(numSegments, segments,
					mother->child1, nodes, max);
				ExtractSegments(numSegments, segments,
					mother->child2, nodes, max);
				ExtractSegments(numSegments, segments,
					mother->child3, nodes, max);
			}
		}
	}
}


DelauneySegments

// Here's where the actual Delauney triangulation
// is done. We return all the edges that are part
// of the Delauney graph.
long DelauneySegments(long numNodes, Node nodes[],
					  Segment *segments[],
					  Connection connections[],
					  long *numDuplicates)
{
	int i;
	long numSegments;
	Node p1, p2, p3;
	double max, dummy;
	double epsilon, negEpsilon;
	// The maximum number of triangles constructed by
	// the algorithm is 9 N + 1
	Triangle *triangles =
		(Triangle*)NewPtr((Size)((9 * numNodes + 1)
							* sizeof(Triangle)));
	Triangle *mother = &(triangles[0]);
	// free is next available position in triangle array
	int free = 1;
	*numDuplicates = 0;
	// The maximum number of edges created by any
	// triangulation is 3 N - 3 - k, where k is the
	// number of points on the boundary of the convex hull
	*segments =
		(Segment*)NewPtr((Size)((3 * numNodes - 3)
							* sizeof(Segment)));
	if ((*segments == NULL) || (triangles == NULL)) {
		DebugStr("\pNot enough memory");
		return -1;
	}
	// Initialize mother triangle - steps 1 and 2 in book
	max = 0;
	for(i = 0; i < numNodes; i++) {
		if (nodes[i].x > max) max = nodes[i].x;
		if (nodes[i].y > max) max = nodes[i].y;
		if (nodes[i].x < -max) max = - nodes[i].x;
		if (nodes[i].y < -max) max = - nodes[i].y;
	}
	// multiply max because I like a safety margin
	epsilon = max * 1e-12;
	negEpsilon = - epsilon;
	max *= 1.1;


	// and find the coordinates of the special triangle
	dummy = max * 3;
	p1.x = dummy;
	p1.y = 0;
	p2.x = 0;
	p2.y = dummy;
	p3.x = - dummy;
	p3.y = - dummy;
	MakeNewTriangle(mother, &p1, &p2, &p3,
					NULL, NULL, NULL);
	// I should shuffle the input points if I
	// really want to avoid worst case behavior
	for(i = 0; i < numNodes; i++) {
		Node *p = &(nodes[i]);
		// First find the "leaf" triangle that contains p
		Triangle *t = FindTriangle(p, mother, negEpsilon);
		if (isInTriangle(p, t))
		{
			addPointInsideTriangle(p, t, triangles,
								   &free, max);
		}
		else // we have a degenerate case
		{
			Triangle *t2 =
				FindTheOtherTriangle(p, t, epsilon);
			if (t2 != NULL)
			//the point is on a shared edge, in which
			// case we find the other triangle and continue
			{
				t->child1 = &(triangles[free++]);
				t->child2 = &(triangles[free++]);
				t2->child1 = &(triangles[free++]);
				t2->child2 = &(triangles[free++]);
				Divide2TrianglesInto2(t, t2, p);		
				// the 2 child1 triangles have a common edge
				// the 2 child2 triangles have a common edge
				LegalizeEdge(t->child1, t->child1->bc,
							 triangles, &free, max);
				LegalizeEdge(t->child2, t->child2->bc,
							 triangles, &free, max);
				LegalizeEdge(t2->child1, t2->child1->bc,
							 triangles, &free, max);		
				LegalizeEdge(t2->child2, t2->child2->bc,
							 triangles, &free, max);
			}
			else
			// We have a duplicate point - I just connect
			// it up right away and forget about it
			{
				Node *q = FindMultipleVertex(p, t, epsilon);
				connections[*numDuplicates].index1 = i;
				connections[*numDuplicates].index2 =
					i + q - p;
				*numDuplicates += 1;
			}
		}
	}
		// Traverse the tree to build the list of edges
	numSegments = 0;
	ExtractSegments(&numSegments, *segments,
					mother, nodes, max);
	DisposePtr((char*)triangles);
	return numSegments;
}
///////
// This was my first solution that naively calculated all
// possible distances. It requires a lot of memory and
// is a very slow, but it is a lot easier to debug.
///////
/*
long AllSegments(long numNodes, Node nodes[],
				 Segment *segments[])
{
	long i, j, k;
	long numSegments = numNodes * (numNodes - 1) / 2;
	

	*segments = (Segment*) NewPtr((Size)(numSegments *
									sizeof(Segment)));
	if (segments == NULL)
		return -1;
	k = 0;
	for(i = 0; i < numNodes - 1; i++)
		for(j = i + 1; j < numNodes; j++) {
			double dx = nodes[i].x - nodes[j].x;
			double dy = nodes[i].y - nodes[j].y;
			(*segments)[k].c.index1 = i;
			(*segments)[k].c.index2 = j;
			(*segments)[k].distSq = dx * dx + dy * dy;
			k += 1;
		}
	return numSegments;
}
*/


 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.