Tuesday, April 17, 2012

Brilliant 8-phase multi-quine in ruby

Wikipedia defines quine as:
A quine is a computer program which takes no input and produces a copy of its own source code as its only output.
In layman terms, it is a program that when executed outputs itself. Like a C program outputting its own source code. Kleene's Recursion Theorem proves the existence of quines in any Turing Complete Language. Its a good exercise to write one in your favorite language. Its fascinating to see quines.

Today morning my friend Umesh showed me this brilliant piece of ruby code that behaves as a Multi-quine. Link to original post by its author. Here's a listing of the same:



Save it as "test.rb" and run the following shell script:
while true;
do
    clear
    ruby test.rb | tee test2.rb
    mv test2.rb test.rb
    sleep 1
done

You will be able to see the picture changing after every 1 second and returning back to the original after 8 seconds. Note that when you run test.rb, it produces the output which is used for the next iteration. The shell script code lines 4 and 5 runs the code and uses the output of the code to replace the original code.

After being amazed by the beauty of this piece of code, I am not trying to figure out how exactly does it achieve this result. Someday I will post the same code with indentations and explanations in this blog.

Tuesday, April 03, 2012

Make Your Own Command-line Calculator with bc

I do not know about you, but I am bothered by the lack of a proper command line calculator for doing small single line calculations in Linux (or any other UNIX or Mac system). Sure bc is there but it does not support floating point by default, so one ends up writing things like:
echo "scale=3; 22/7" | bc
which is quite cumbersome for day to day work.

To subvert this trouble, I wrote the following two-liner and saved it as "calc" in a directory in PATH:
#! /bin/bash
echo "scale=3; $1" | bc; exit
Then do a "chmod +x" on the file to give it execute permission. This does the same thing as the above script, but is way simpler to use:
calc 22/7
The command "scale=3" was to instruct bc to print upto 3 decimal digits. You can change it as per your requirements.

The bc utility can do way more than this simple calculations. For example it can handle different bases and load functions from files. To know more about its capabilities try the good old "man bc" in terminal or read an online reference like this one on about.com.  You can read more about its advanced capabilities from an old but quite relevant article in LinuxJournal "bc: a handy utility".

Disclaimer : Although the script was by me, the idea is not new. In fact a lot of my colleagues use similar scripts for their own daily work.