Tag Archive for 'Useless'

Pascal’s Triangle

Grant Muller writes that Algorithms can Really Beat You:

I stared at the pyramid of numbers scribbled hastily in blue dry erase. The only thing clear to me in that moment was that I wouldn’t have this figured out in five minutes. Or even ten.

“Any number in the pyramid, or in this case tree array, is the sum of the two numbers above it,” the young man continued, “write a function that gets the value of any x, y coordinate in this structure.”

Sitting quietly in the middle of that article was an old friend of mine, Pascal’s Triangle, that I encounter every so often when doing nerdy things with equations.

The first rows in Pascal’s Triangle are 1, 11, 121, 1331 and 14641 — the most observant will notice that those are the values of 110, 111, 112, 113 and 114. In fact, if you consider the values of the sixth row, 1-5-10-10-5-1, they correspond to the number 161051, which is 115.

And the reason for this is the way in which Pascal’s Triangle is constructed: take a row, duplicate it, shift one copy to the left by one, and add them together.

  1 1           1 2 1         1 3 3 1
+   1 1       +   1 2 1     +   1 3 3 1
= 1 2 1       = 1 3 3 1     = 1 4 6 4 1

This is the same as saying that «any number is the sum of the numbers above it», or T(x,y) = T(x-1,y-1) + T(x,y-1). As an amusing side-effect of this construction method, the sum of all numbers in a given row is always a power of two — by adding two copies of the previous row together, you are multiplying that sum by two every time. Remember this tidbit, it will come in handy later on.

What does this have to do with the powers of 11 ? Well, to multiply by 11, you would multiply by 10 (which is easier: shift all the digits to the left) and add the original number. So, multiplication by 11 works in exactly the same way as the Pascal’s Triangle. Which is why the numbers are the same.

Another place where Pascal’s Triangle appears is binomial coefficients:

(a + b)2 = 1 a2 + 2 ab + 1 b2
(a + b)3 = 1 a3 + 3 a2b + 3 ab2 + 1 b3
(a + b)4 = 1 a4 + 4 a3b + 6 a2b2 + 4 ab3 + 1 b4

To expand (a + b)n, all you need to know is the values on row n of the Triangle. And the reason for this is exactly the same as the one for 11 (and in fact, 11 is a special case of the binomial formula where a=10 and b=1).

But that’s not all. Let’s discuss something entirely different for a second — the fun thing about math is precisely that you can start exploring entirely different venues and end up where you started anyway. So, suppose you have a N-bit integer, and you wish to count how many such integers have exactly M bits set to 1. This is number is known as «N choose M», and is fairly frequently found in mathematics. How do you do determine that number?

One way, the combinatorics approach, is to determine an algorithm that generates such a value, and count how many independent possible choices that algorithm had. My algorithm in this situation is «pick one bit at random, set it to 1, repeat M times»

For the first step, there are N possible bits to choose from.

For the next step, there are N-1 possible bits, and so on until only N-M bits are left. So, there are N × (N-1) × (N-2) × (N -3) … (N-M+1) possible runs for this algorithm. This can be written more concisely using factorials : N! / (N-M)!

But wait! This algorithm actually generates each set of bits several times: once for every possible order of selection of those bits — which is known to be M! for a set of M bits. So, the actual number of distinct runs of my algorithm is N! / ( M! × (N-M)! )

This is something we learn in high school in France, or at least we did back when I was still in high school.

The other way to determine this number is to solve that problem recursively: let’s say that there are C(N,M) different N-bit integer with M bits set to 1. For each such integer one of two possible cases happens:

  • It consists of a 0 followed by an (N-1)-bit integer with M bits set to 1. There are C(N-1,M) such integers.
  • It consists of a 1 followed by an (N-1)-bit integer with (M-1) bits set to1. There are C(N-1,M-1) such integers.

So, recursively, C(N,M) = C(N-1,M) + (N-1,M-1), with the edge cases being C(N,N) = C(N,0) = 1 (there’s only one integer with all-zeroes, and only one integer with all-ones). This is the same formula as Pascal’s Triangle !

T(x,y) = C(N,M) where y = N and x = M

So, here’s the pseudocode for a function that correctly computes T(x,y) far faster than the recursive version suggested by Grant, by using the factorial-based definition we found for C(N,M) :

function T(x,y) {
  var num = 1, denom = 1, start = y-x;
  for (i = 1; i <= x; ++i) {
    num = num * (start + i);
    denom = denom * i;
  }
  return num / denom;
}

Last question: what is C(N,0) + C(N,1) + … C(N,N) ? It is merely counting the number of N-bit integers that have any combination of bits set to 1. We know there are 2N integers. Remember when I told you the sum of the elements in a row of the Triangle was a power of two?

Yes, maths are fun like that.

Article Image © PhilosophyGeek — Flickr

RS Latches


One of my oldest memories harkens back to 1989 — I was a four years old boy in communist Romania. My mother has a PhD in biochemistry, and her father and brother both had a PhD in physics, so it might seem quite unsurprising that I followed in their rational and scientific steps, but it would be hard to put the proverbial finger on how, precisely, that happened. This is what that specific memory is about.

It all started with my frequent stays at my grandparents’ house, a conventional second-floor flat in Bucharest, where my grandmother and grandfather took turns babysitting me while my parents were out hammer-and-sickling (well, laboratory-and-architecturing) the socialist ideal. My grandfather was intent on turning me into a bright scientific mind, so he asked my uncle to build me a computer. Nothing fancy, mind you : it had no operating system worth mentioning, no hard drive, and depended on magnetic tapes and 8″ floppies to actually work. My grandfather showed me a standard BASIC interpreter, and had me type in a program that displayed, line by line, an analog wall clock.

Fascinated, I started spending my days on that thing writing BASIC code, learning how to build increasingly complex programs, and starting my career as a programmer. Or so had my grandfather hoped. A few seconds after discovering computer programming, I discovered computer games, which were a far more fascinating novelty than displaying wall clocks on a screen. I promptly forgot about the BASIC interpreter and for nine long years, I assumed that programming computers was some sort of esoteric arcane art, invisible to the uninitiated, and remained entirely uninterested in it.

Instead, my breakthrough as a rational mind was triggered by the close proximity of two unlikely catalysts : one was a frequent diet of mecha anime (the quality of the Romanian dubbing was hilarious), and the other was a cupboard drawer full of bits and pieces that could, to a child’s mind, be spare parts out of which a robot could be built : wheels, small electrical engines, cables, batteries, microprocessors, light bulbs… as a matter of fact, once I had the basic understanding of how a batteries + cables + engine setup worked, I did build small uninteresting contraptions.

I became intensely interested in building a robot myself. Obviously, I did not have the technical skills or the willpower to follow through with this plan, but I would listen, entranced, to any explanations I would receive that were related to robot-building. My grandfather was writing a book on semiconductors at the time, so he showed me a large digital circuit and let me understand that this is what the brain of a robot would look like — only quite larger !

And so he started teaching me the elementary principles of digital circuits. We spent little time discussing the underlying technical details, and instead concentrated on the simpler abstractions of logical gates. This time, I was fascinated. I would grab a pen and paper and draw circuits for fun. The meaning of AND, OR, NOT, NAND, NOR and XOR are imprinted in my brain ever since I was five years old… there are few concepts remaining in my brain that have been there for so long.

My circuits behaved like mathematical functions : I would mentally set the input bits, and the output bits would contain the result, so I could build the truth tables that mapped input combinations to output combinations. I experimented with basic arithmetic functions, learning binary as I went. And then one day my grandfather showed me a circuit that I could draw from memory to this day : the RS latch.

The fun thing about the RS latch is that it cannot have a truth table. It is an entirely different beast from arithmetic “write input bits, read output bits” circuits in that it has a state. If you write 1 to the S input bit, the output becomes 1 and remains 1 until you write 1 to the R bit, at which point the output becomes 0, and so on. To say things differently, the S input bit stands for “Set” and sets the output to 1, and the R input bit stands for “Reset” and sets the output to 0. When both R and S are set to 0, then the latch output bit is equal to whatever it was previously set to.

The RS latch is a versatile little thing. It can be used to implement RAM (one of the first things I did with it), or it can be chained to create an incrementing counter.

After a while, my interest in digital circuits faded, but the effects it had on my character were permanent : I now had experience applying abstract rules to abstract concepts, and it was fun.

Article image © Cornelia Kopp — Flickr

Does this repository make me look fat?

The main RunOrg SVN repository contains:

  • 38490 lines of OCaml implementation code spread over 273 *.ml files.
  • 5134 lines of OCaml signature code spread over 156*.mli files.
  • 4776 lines of HTML template code spread over 271 *.htm files.
  • 1971 lines of CSS in 6 files.
  • 1898 lines of JSON configuration in 26 files.
  • 1172 lines of JavaScript in 5 files.

That’s a total 53441 lines in 837 files.

Here’s a plot of how the 38490 lines of OCaml code came into being over the last eight months.

That is all.

AJAX Tiles Game

I started programming life by writing an AI for a simple game called RoboWar (back when it was a shareware game on Macintosh, in the pre-OS X days). Make sure you click the “Edit” buttons at the bottom of that page to view the kind of code I had to deal with. I then moved on to HyperTalk and, when I finally got my hands on a PC, started a ten-year spree in C++.

Recently, I started toying with a similar idea: to create a game where people could write an AI that would play for them, with simple and easily modeled rules, and a really easy way to share your creations with your programmer friends (because just adding your AI to a long list of other AIs is kind of boring and not very social).

So, I wrote a simple game in JavaScript. You feed it one URL for each player, and the game connects to that URL and asks for the next move. So, your AI is one URL, which makes it easy to share. Not to mention that you can probably write that AI in any language you wish, provided it can respond to HTTP requests and read JSON arrays of characters, and you can resort to a lot of fancy stuff (cloud computing, learning from experience, genetic algorithms) that would otherwise not be available in a game like RoboWar. The game board is readily available for you to observe while the game is played. It looks like this:

The rules to the game are fairly simple: pick white tiles to paint them with your color, pick tiles you already own to nuke them (blows up that tile and the four adjacent tiles as well), and connect a large group of tiles you own to a small group of tiles your opponent owns to conquer them. The player with the most tiles when the board is covered, wins. Play it here. I’ve already programmed four different AIs:

  • http://tiles.nicollet.net/ai/?random plays randomly.
  • http://tiles.nicollet.net/ai/?expand creates one single group of tiles and expands it as fast as possible.
  • http://tiles.nicollet.net/ai/?fearful nukes its own tiles when they might become connected to enemy tiles.
  • http://tiles.nicollet.net/ai/?contain attempts to contain the enemy in a prison of nuked tiles.

None of these are particularly good, and a human player can certainly beat them quite easily, but they’re a good challenge for your own AI. If you wish to participate without starting from scratch, you can fork the sample AI on GitHub to create your own (it’s PHP code). Also, the GitHub README contains all the technical details about what data your AI URL receives and what data it should respond with. And, if you’re curious, the game rules are cleanly described in the JavaScript source code.

I’m looking forward to hearing from you. Please share your AIs in the comments below, if you please: I’m really interested in what you might come up with.

Boo.

It was early february a few years ago. My girlfriend had just left France, and was to stay in China for six months, so I was getting back to my old teen programmer habits of writing code alone at my desktop computer at 4:00 am. My room was the typical no-girlfriend-around mess, with old clothes lying on the bed, dishes on the corner of the desk, unused laptops scattered around the room, soft music in my headphones and my two monitors being the only light source in the room.

I’m afraid I don’t really remember in what order things did happen that night. I do remember hearing a short, sad whistle coming from behind me, feeling something soft, large and warm pressed against my lower back, and all the lights suddenly going out, all in quick succession.

I immediately stood up and turned around, my not-yet-wireless headphone cord dragging unidentified objects off the desk into a cacophonous cascade, my badly adjusted eyes trying to see through the darkness to understand what had just touched me, or where that noise might have come from.

So I just stood there for a while. After a few seconds, I heard a noise, different from the first one. It sounded like fingernails on plastic. I could not precisely locate where it was coming from, and it was so soft that I quickly dismissed it as either a by-product of my terrified imagination or one of the fallen objects rolling around.

Then, I heard that same noise again ten seconds later. And again every ten seconds after that. It did not sound like anything a machine could make (and besides, all appliances and computers were powered off anyway), in fact it had an almost human feel to it.

I called out “Il y a quelqu’un?” (“Is anybody there?”), then immediately felt silly at asking such a question out loud while alone at night in my apartment. My question was shortly followed by a short male laughter coming from somewhere in my room. Then the finger-on-plastic noise again. And again.

It occurred to me that having a panic attack in the dark was not very advisable, and that I could at least use one of my laptops as a light source. I found one, picked it up, placed it on the desk and opened the lid. The screen came to life showing a browser pop-up window for some online poker playroom (don’t judge me!) that bathed the room in a pale green light. I started looking around for my flashlight, which would provide better illumination and let me reach the fuse box, when I heard someone distinctly laughing right behind me.

I turned around, striving to drive my elbow into what I hoped to be a sensitive part of the intruder’s anatomy and ended up being a lot of otherwise uninhabited air. And I notice a video playing on the poker pop-up, of a smug man like you expect to see on a poker pop-up, juggling with some poker chips in his hand and making that fingernail-on-plastic noise. And laughing every ten animation loops. Genius.

From what I gathered the next day, the power had been cut in the middle of the night, prompting my alarm clock to whistle loudly in its death throes. The laptop had been playing that poker video since I laid it down, but the sound had been drowned out by the music in my headphones and only became audible when the music stopped and I took them off. I still have no idea what the warm sensation was.

Also, you might want to read this [reddit].

Gifts

Are you having trouble with the search for presents for everyone around you? Worry no longer : this one-page helpful guide will take you through the difficult steps of having a great idea, and provides helpful tips for escaping from the melee on the morning of December 25th.

Creative Commons License
The font used for the headings is Tusj, and there’s a link to a downloadable and printable PDF file here. And don’t forget to support the Switzerland.

Ovh-WikiLeaks sets a Reassuring Precedent

I mentioned recently that Amazon ousted WikiLeaks from its servers without waiting for a confirmation of its illegality, and how this implied huge risks for anyone using the Amazon Cloud.

So, WikiLeaks moved elsewhere, and one of these locations was OVH, a hosting company in France that happens to host the RunOrg servers as well. As expected, a combination of public outcry and government pressure appeared as soon as the location of the WikiLeaks hosting was revealed on Thursday, December 3rd.

The OVH CEO, Octave Klaba, penned a response to the ongoing crisis the next day, which I have translated into english for your convenience.

Hello,
As you certainly know, the wikileaks site is hosted on our infrastructure since yesterday in the early morning. A client ordered a dedicated server with RIPE blocks and protection against attacks. Their bill, paid with a credit card, is less than 150 euro. And that client hosts the wikileaks site. On a strict legal definition, Ovh does not host that site. Ovh is only the technical support of the technical solution that said client has ordered.

In short, this is an ordinary and daily occurrence. The [ordering and delivery] system is entirely automatic and works 24/7. We discovered just like you did that this site was on our infrastructure yesterday … in the media.

Ovh is neither condones nor condemns this site. The question is off topic. Ovh is a company that provides infrastructure, the famous cloud computing available within hours …, and our role is to provide this technical service. That is all. We did not ask to host, or not to host, that site. Now that they’re using our infrastructure, we will honor the contract. That is our job. The site works.

Given the recent political statements, and the increasing pressure put on us even here in Roubaix Valley, we have decided to refer the topic in emergency to a judge, who could then determine whether this site may legally be hosted on French soil. It is the role of neither the political world nor Ovh to demand or decide the removal of a site, that is the role of judges alone. That is how it should work in a state of law.

We hope that the judge will take a decision tonight or tomorrow. And Ovh will apply that decision immediately.

All the best,
Octave

I am overjoyed to see that, at least in my country, my web site will not be ousted from the servers that are hosting it unless a judge says so, regardless of the political or economical pressure. I guess that’s too bad for Amazon.

Here’s the original French text, for those interested:

Bonjour,
Comme vous savez certainement, le site wikileaks est hébergé sur nos infrastructures depuis hier très tôt le matin. Il s’agit d’un client qui a commandé un serveur dédié, avec les blocs RIPE et de protections contre les attaques. Sa facture payée par CB s’élève à moins de 150euro. Et donc il héberge le site wikileaks. Juridiquement parlant Ovh n’est pas l’hébergeur de ce site. Ovh est, juste, le prestataire technique de la solution technique que le client a commandé.

Bref, l’histoire est banale et quotidienne. Le système est totalement automatique et fonctionne 24 heures sur 24. Nous avons découvert comme vous tous que ce site est chez nous hier … dans la presse.

Ovh n’est ni pour ni contre ce site. La question hors sujet pour nous. Ovh est une entreprise qui fournit les infrastructures, le fameux cloud computing disponible en quelques heures …, et notre rôle est d’assurer cette prestation technique. C’est tout. On n’a pas demandé d’héberger ce site ou ne pas l’héberger. Maintenant qu’il est chez nous on assure le contrat. C’est notre boulot. Il est fonctionnel.

Compte tenu de dernières déclarations politiques, et de pressions qui commencent réellement à se sentir, même ici à Roubaix Valley, nous avons décidé de saisir le juge en référé afin qu’il se prononce sur la légalité ou pas de ce site sur le territoire français. Ce n’est pas au monde politique ni à Ovh de demander ou de décider la fermeture ou pas d’un site mais à la justice. C’est comme que ça doit marcher dans un pays de droit.

Nous espérons que le juge donnera sa décision avant ce soir ou demain. Et Ovh appliquera la décision immédiatement.

Amicalement
Octave

Be Careful What You Ask For

Jumo is a brand new social network that lets you connect with the causes and organizations that you support. They started their open beta recently, so I chimed in to see what was going on over there.

I didn’t get past the signup form. Not because of any bugs or technical difficulties, but because of this:

So, it turns out that to connect to Jumo, you need to have a valid Facebook account. Why not? Letting your users connect through Facebook is a good strategy to gather information easily (it lets the user import his personal information from Facebook instead of typing it by hand). Requiring a Facebook account is probably a bit too extreme in my opinion, especially when it’s technically unnecessary, but I can live with it, especially since my Facebook profile is designed to contain only public information.

The showstopper here is that I need to grant permission to post on my wall. I’m utterly and irrevocably paranoid about my online image, so anything that looks like me saying things I don’t actually want to say is grounds for immediate rejection. I have absolutely no idea what Jumo is going to do with this permission once granted, and the last few times I’ve seen that permission granted by my friends, shady applications flooded their walls with advertising for other third party sites said friends knew nothing about. I’m pretty sure Jumo is not going to do that, but them asking for permission can only mean one thing: sooner or later, a message from Jumo will appear on my wall without letting me review its contents first.

Ultimately, this is a gamble: by asking for wall access, Jumo is willingly throwing away all the reputation-obsessed people who will not grant that permission, but earns the right to post a message on the walls of all those people who don’t care enough about Jumo to write that message of their own accord. And they’re playing their cards just right, because people like me are a minority. But that doesn’t mean it’s not a cheap, dirty trick.

Sorry About That

Welcome to a geek’s worst nightmare: the server just went down. There’s no more blog, no more web site, no more safe online backup of your family pictures, and your victor@nicollet.net e-mail is deader than a wooden piece of… wood. Turns out, my hosting company had a little accident where hard drives suddenly couldn’t be written to anymore.

Now, of course, nicollet.net is not what I would call a production server. On a real-life production server where the disk cannot be written to, sirens would start wailing, system administrators would be paged in the middle of the night (on a week-end), monitoring software would send cryptic apocalypse prophecies in their summary e-mails, and statues would cry blood. For my blog, everything continued to work in read-only mode for what appears to be half a day, until I decided to log in to the server and found out I couldn’t.

So, I rebooted it (from my hosting company’s online administration tool) and waited for it to come back up so I could investigate.

It didn’t. For half an hour. I kept refreshing the web page that shows the server status in my hosting company’s server rooms (mine is in 08H06) until I found out the page refreshed itself automatically.

And when it came back online, I stumbled upon the geek’s second worst nightmare: the private key of my server had been changed. In non-geek terms, this means that the server had been replaced by another server, possibly as a consequence of a hostile take-over by a random hacker (I’ve had this happen, and it’s very annoying) or an unexpected hard drive re-format.

After a few minutes of frantic searching, it appeared that my server had been replaced by a special rescue server that I was allowed to use to salvage whatever I could from the smoldering heap of its former self. That server, of course, had a special password that was sent to me on my e-mail address. All of you who guessed victor@nicollet.net, you get a cookie. All my attempts to have that password sent to another address failed miserably, until I finally gave up (because I have, you know, a Start-Up to start up).

It took about 12 hours for my hosting company to find out what happened, revert the changes and reboot my server. No data was lost (except for that e-mail that Steve Jobs sent me about our secret project together, which I guess I’ll never get), and everything works like a charm.

What If They Made Movies?

Amazon. They direct, produce and/or publish every single movie made since the beginning of cinematography. By sifting through your recent movie-viewing habits, Amazon are able to suggest the exact movie that will interest you the most, which you can then order with their one-click ticket purchase patented interface. They will then send you daily e-mails about that movie and other similar ones for the rest of your life.

American Airlines. The trailers hinted at a light-hearted romantic comedy, but the movie ends up being a three-hour claustrophobic thriller. The food served in the movie theater is horrible, and every patron ends up paying a different price for their ticket, plus a carry-on luggage fee. The lines at the theater are longer than for other movies, but that is mostly because you need a full-body scan because you can be allowed in.

Apple. This year’s iMovie was found in a New York bar after what appears to be two years of top secret development. Evangelists announce that it will change the way people watch movies, and that it will be available soon in a single movie theater chain to be identified at a later date. The DVD will of course only be compatible with genuine Apple products. The word on the street is that you cannot watch the movie if you rest your head on your left palm, but Steve Jobs said that’s the case for all other movies and you will get a free movie-watching glove to compensate for it.

British Petroleum. A profitable studio for years because you just had to see their movies despite their sky-high price, despite protests from hippies and tree lovers. Recently moved from their middle eastern movie sets back to the southern United States, but managed to annoy the locals in a badly thought through PR stunt. Now, they spend more money on appeasing the inhabitants than they spend on actual movies.

Dell. Not available in any movie theater. Instead, you can build your movie online by choosing cast members, plot elements and special effects from a list, and it gets delivered to you on DVD within a few days. The Angelina Jolie component (at +$9999) has been recently announced and widely acclaimed as a smart move.

Facebook. It’s like that anti-war rally scene from Forrest Gump, except you can tag all your friends right there in the movie. The studio managers pride themselves about being the fastest growing movie studio around and sweep under the rug any concerns about scenes from private amateur videos being made available to the general public. They’re currently considering a movie about themselves.

Google. They don’t make movies. Instead, they build super-computers that run super-algorithms that create the movie you want by spying on your browsing habits. SEO (SEenOntelevision) consultants now try to trick the super-algorithms into including product placement in the movies Google creates. The studio recently introduced a new way of watching movies: based on your reactions as you watch the movie,  the plot changes to fit your mood.

NASA. Ever since their hour of glory with their 1969 best-seller, they have been doing silly re-hashes such as «Dude, Where’s My Shuttle?», «Dude, Where’s My Venus Probe?» and «Dude, Where’s My Mars Rover?» that absolutely no one wants to watch anymore, despite every single one having a budget that puts James Cameron to shame. Recently, people have started making fun of their 1969 movie sets and how fake they look.

Nintendo. This japanese studio tries to revolutionize the way people watch anime by introducing interactive features in the viewing experience: the WiiSee comes with a popcorn-shaped controller you can use to simulate eating popcorn, and a straw-shaped controller you can use to simulate drinking beverages.

People’s Republic of China. They seem to only make movies about how great they are and how happy the actors happen to be. Cast members are forbidden from viewing movies from other studios, to keep their minds pure and honest. Their movies somehow net more profits in a single week-end than any other movie in a week, and they never get a single negative review—except that one time, but the reviewer said he was mistaken and then commited «suicide»

Twitter. A micro-filming studio, produces movies shorter than 140 seconds that somehow everyone feels obliged to share and reply to.

Wikipedia. A huge studio made up mostly from volunteers, they only publish documentaries about silly esoteric things such as rotoscopes or lycaenidae. They are known for the huge amount of editors on every single movie, and the insane bickering  between them.

Have any other suggestions? Let me hear them!



1170 feed subscribers
(readers who polled a feed this week)