I first read about quines several years ago but have never gotten around to trying to write one. I decided to write it in my language of choice, C/C++, and more specifically C to keep it as simple as possible. The code could be shorter, in fact I’ve seen one liner Quines written in C. But I wanted to keep proper formatting and commenting and to have this formatting persist in the result of running it.
The Quine works by creating a C-String with the initial scaffolding of the program. However, where the redefinition of this inner string would occur we instead use the string formatting phrase %s which tells the printf function to insert the value of another C-String in it’s place. By doing so we can then pass our string s to printf twice, once as the string format, and a second time as the value for injection where the %s flag is. We also use the same trick with the %c flag which injects a single character to inject the hex-values of the new-line character \n or 0x0a and the quote character \" or 0x22. By using the hex-values instead of the escaped literals we don’t have to worry about escaping the inner string while printing to stop the backslashes from being evaluated.
This program takes (from stdin) a value N followed by N lines representing a graph structure where each line consists of an integer id followed by an arbitrary number of integers representing the id’s of the bordering nodes.
The program then computes and outputs a list of the nodes (in the order they were entered) with a colour value ranging from 0..k such that each node has a unique colour to it’s bordering nodes.
This program expects 4 arguments to be passed in on the command line representing the location (as xy coords) of two circles. The program then computes the total area covered by the two circles including any possible overlap between them and prints the area to the console.
Despite the fact that this problem can be solved numerically in constant time using the equation:
D = sqrt( (x-u)^2 + (y-v)^2 )
A = (2 * PI) - (2 * ACos( D / 2 )) + (D / 2) * sqrt( 4 - D^2 )
I thought it would be more of a programming challenge to write a simple monte carlo simulation to solve for the area. The simulation can easily be modified to allow an arbitrary number of circles to be inputed at varying radii.
I decided to start taking part in some of the programming challenges over at /r/dailyprogrammer. The first of which was to read in an input file representing an edge/node graph structure of the form:
0 -> 1
1 -> 2
2 -> 4
3 -> 4
0 -> 3
And to output the Adjacency Matrix of the graph in the form:
0 1 0 1 0
0 0 1 0 0
0 0 0 0 1
0 0 0 0 1
0 0 0 0 0
Below is the code of my submission. I decided to make the challenge a little more interesting using bit level operations to store the matrix in ~approx~ N*N bits rather than the usual minimum of N*N bytes.