TweetFollow Us on Twitter

Jul 99 Challenge

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

by Bob Boonstra, Westford, MA


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" {

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)

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;


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


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,
	*numIntermediateNodes = 0;

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


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


// 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]);


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;



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


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


// 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);


// 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);


// 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);


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


// 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");


// 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");


	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");


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


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


// 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);


// 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 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))
	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)
	// If one of the opposite vertices is special, we
	// don't flip the edge between the two common points 
	if (o2Special || o1Special)
	// 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);


// 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));


// 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,
	if ((triangle->child2 != NULL) &&
		isOnTriangle(p, triangle->child2, negEpsilon))
			return FindTriangle(p, triangle->child2,
	if ((triangle->child3 != NULL) &&
		isOnTriangle(p, triangle->child3, negEpsilon))
			return FindTriangle(p, triangle->child3,
	DebugStr("\pProblem in FindTriangle");
	return NULL;


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


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


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


// 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;
				ExtractSegments(numSegments, segments,
					mother->child1, nodes, max);
				ExtractSegments(numSegments, segments,
					mother->child2, nodes, max);
				ExtractSegments(numSegments, segments,
					mother->child3, nodes, max);


// 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,
	// 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);
			// 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);
	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 *
	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

WhiteCap 6.7.1 - Visual plug-in for iTun...
WhiteCap is a sleek and sophisticated music visualizer and screensaver that features futuristic, wireframe mesh visuals with dynamic backgrounds and colors. WhiteCap contains thousands of visual... Read more
DiskMaker X 6.0 rc5 - Make a bootable OS...
DiskMaker X (was Lion DiskMaker) helps you to build a bootable drive from the official OS X installer app (the one you download from the Mac App Store). It detects the OS X Install program with... Read more
Lyn 1.9 - Lightweight image browser and...
Lyn is a fast, lightweight image browser and viewer designed for photographers, graphic artists, and Web designers. Featuring an extremely versatile and aesthetically pleasing interface, it delivers... Read more
MacFamilyTree 8.2.1 - Create and explore...
MacFamilyTree gives genealogy a facelift: modern, interactive, convenient and fast. Explore your family tree and your family history in a way generations of chroniclers before you would have loved.... Read more
LaunchBar 6.9 - Powerful file/URL/email...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
LaunchBar 6.9 - Powerful file/URL/email...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
MacFamilyTree 8.2.1 - Create and explore...
MacFamilyTree gives genealogy a facelift: modern, interactive, convenient and fast. Explore your family tree and your family history in a way generations of chroniclers before you would have loved.... Read more
Spotify - Stream music, crea...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
VOX 2.8.26 - Music player that supports...
VOX just sounds better! The beauty is in its simplicity, yet behind the minimal exterior lies a powerful music player with a ton of features and support for all audio formats you should ever need.... Read more
beaTunes 5.0.1 - Organize your music col...
beaTunes is a full-featured music player and organizational tool for music collections. How well organized is your music library? Are your artists always spelled the same way? Any R.E.M. vs REM?... Read more

Latest Forum Discussions

See All

This War of Mine gets a new ending and m...
This War of Mine just got a big new update, featuring free DLC that adds a new ending to the game, among other exciting changes. The update is celebrating the game's two-year release anniversary. Apart from the new ending, which will be quite... | Read more »
Summon eight new heroes in Fire Emblem H...
Nintendo keeps coming at us with Fire Emblem Heroes updates, and it doesn't look like that trend is stopping anytime soon. The folks behind the game have just announced the new War of the Clerics Voting Gauntlet, expected to start next Tuesday. [... | Read more »
The best deals on the App Store this wee...
iOS publishers are pulling out all the stops this week -- there's a huge number of seriously great games at discounted prices this week. Let's not waste any time and get right down to business. [Read more] | Read more »
The House of da Vinci (Games)
The House of da Vinci 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: Enter The House of Da Vinci, a new must-try 3D puzzle adventure game. Solve mechanical puzzles, discover hidden... | Read more »
Solve the disappearance of history’s gre...
Blue Brain Games invites you to indulge in an immersive hands-on 3D puzzle adventure in similar vein to The Room series, with its debut release The House of Da Vinci. Set during the historic period of the Italian Renaissance (when Leonardo himself... | Read more »
Age of Rivals (Games)
Age of Rivals 3.3 Device: iOS Universal Category: Games Price: $.99, Version: 3.3 (iTunes) Description: Deep civilization-building strategy in a fast-paced card game! | Read more »
Panthera Frontier (Games)
Panthera Frontier 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: | Read more »
Angry Birds Evolution beginner's gu...
Angry Birds changes things up a fair bit in its latest iteration, Angry Birds Evolution. The familiar sling-shot physics mechanics are still there, but the game now features team-based gameplay, RPG elements, and a new top-down view. With all of... | Read more »
Sega Forever is for the retro game fans
Sega is launching a new retro games service titled Sega Forever, in a move that's sure to delight games enthusiasts with a bit of nostalgia. Sega's releasing five classic games for free. The titles include Sonic the Hedgehog, Phantasy Star II,... | Read more »
The Little Acre (Games)
The Little Acre 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: | Read more »

Price Scanner via

ABBYY TextGrabber 6 for iOS Implements Instan...
ABBYY has announced the release of TextGrabber 6.0.0, an important feature update to the company’s productivity app developed for iOS and Android devices. TextGrabber 6.0 now offers Real-Time... Read more
vPhone, First Smartphone That Can’t Be Lost,...
Austin, Texas based Hypori has introduced the vPhone, a virtual smartphone that affords every business user the benefits of separate work and personal phones, conveniently delivered on a single... Read more
Save this weekend with 2016 refurbished MacBo...
Apple has dropped prices on Certified Refurbished 2016 15″ and 13″ MacBook Pros by as much as $590 off original MSRP. An Apple one-year warranty is included with each model, and shipping is free: -... Read more
New 27-inch 3.4GHz iMac on sale for $1699, sa...
MacMall has the new 2017 27″ 3.4GHz iMac (MNE92LL/A) in stock and on sale for $1699 including free shipping. Their price is $100 off MSRP. Read more
Clearance 2016 MacBook Pros available for up...
B&H Photo has clearance 2016 13″ and 15″ MacBook Pros in stock today and on sale for up to $400 off original MSRP. Shipping is free, and B&H charges NY & NJ sales tax only: - 15″ 2.7GHz... Read more
Apple Ranks 9th In comScore Top 50 U.S. Digit...
comScore, Inc. has released its monthly ranking of U.S. online activity at the top digital media properties for May 2017 based on data from comScore Media Metrix Multi-Platform. * Entity has... Read more
10.5-inch iPad Pros available for up to $20 o...
B&H Photo has the new 2017 10.5″ iPad Pros available for up to $20 off MSRP including free shipping plus NY & NJ sales tax only: - 64GB iPad Pro WiFi: $649 - 256GB iPad Pro WiFi: $749 - 512GB... Read more
Three Off-The-Beaten-Track iOS Apps That Dese...
One of the great things about using iPads and iPhones is the vast selection of apps available for most anything you want or need to do. The three outlined in this article have been in my core app... Read more
Apple No. 1 Spot In Gartner Top 100 Vendors i...
Gartner, Inc. has unveiled the top global 100 vendors in IT in 2016 based on their revenue across IT (excluding communication services) and component market segments. In the Gartner Global Top 100:... Read more
Clearance iMacs available for up to $300 off...
B&H Photo has clearance 21″ and 27″ Apple iMacs available starting at $949, each including free shipping plus NY & NJ sales tax only: - 27″ 3.3GHz iMac 5K: $1999 $300 off original MSRP - 27″... Read more

Jobs Board

*Apple* News Product Marketing Mgr., Publish...
…organizational consensus on strategy and vision for publisher tools, authoring, and Apple News Format.Carries this strategy and vision across the organization to Read more
*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Security Data Analyst - *Apple* Information...
…data sources need to be collected to allow Information Security to better protect Apple employees and customers from a wide range of threats.Act as the subject matter Read more
Lead *Apple* Solutions Consultant - Apple I...
…integrity, and trust.Success Metrics/Key Performance Indicators:Quantitative* Year over Year growth in Apple Product and Beyond the Box sales in the assigned Point of Read more
*Apple* Solutions Consultant till v%u00E5r...
…ethics, integrity, and trust.Success Metrics/Key Performance Indicators:QuantitativeYear over Year growth in Apple Product and Beyond the Box sales in the assigned Point Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.