PostScript – a quick way to visualize algorithms

Sometimes (for example during a programming contest) there is a need of a quick tool for visualizing outcome of an algorithm.
PostScript might be a very useful tool then.

Here is a basic PostScript file:

3 setlinewidth 
% creating  a square
200 200 moveto
400 200 lineto
400 400 lineto
200 400 lineto
200 200 lineto
% drawing a square
% creating a circle located in (300,300) with radius 100
300 300 100 0 360 arc 
% drawing a square

You should save it with extension .ps and open using Evince under Linux or GhostView under Windows.

Using this small set of commands: moveto, lineto, stroke, showpage, you can quickly vizualize your geometrical algorithms.
Here is example of creating an Archimedean spiral PostScript file in C++:

#include <cstdio>
#include <cstdlib>
#include <cmath>
using namespace std;
FILE * fin;
void spiral(double xstart, double ystart, double radius, double a, double b){
	fprintf(fin, "%f %f moveto\n", xstart+b, ystart);
	for(double fi=0.0; b+a*fi<=radius; fi+=0.1){
		double r = b+a*fi,
				 x = xstart + r*cos(fi),
				 y = ystart + r*sin(fi);
		fprintf(fin, "%f %f lineto\n", x, y);
int main(int argc, char ** argv){
	double x, y, radius, a, b;
		printf("USAGE: ./spiral X Y R A B\n");
		x = 300; y=300; radius=200;
		a = 3; b= 40;
	} else{
		x = atof(argv[1]); y=atof(argv[2]); radius = atof(argv[3]);
		a = atof(argv[4]); b = atof(argv[5]);
	fin=fopen("", "w");
	fprintf(fin, "%%!PS\n");
	fprintf(fin, "3 setlinewidth\n");
	spiral(x, y, radius, a, b);
	fprintf(fin, "stroke\n");
	fprintf(fin, "showpage\n");	
	return 0;

Parameter a adjusts “density” of lines in a spiral.
Parameter b adjusts “hole” in the center of a spiral.

Web resources:
Simple PostScript commands pt. 1
Simple PostScript commands pt. 2
An introduction to PostScript

This entry was posted in Algorithms, C++ and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *