Archive for the 'Random' Category

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

Steve Jobs

Today, the front page of Hacker News only mentions one topic.

1. Steve Jobs has passed away. (apple.com)
2. Steve Jobs has died (marketwatch.com)
3. The Steve Jobs I Knew (allthingsd.com)
4. President Obama on Steve Jobs: “He Changed the Way Each of Us Sees the World” (whitehouse.gov)
5. Bill Gates on Steve Jobs (thegatesnotes.com)
6. Thanks, Steve (samaltman.com)
7. Apple RIP Logo design (jmak.tumblr.com)
8. Sergey Brin on Steve Jobs (google.com)
9. Tim Cook: “No words can adequately express our sadness at Steve’s death” (arstechnica.com)
10. Larry Page on Steve Jobs (google.com)
11. Google’s Steve Jobs tribute (google.com)
12. Bill Gates Makes Statement on Steve Jobs (google.com)
13. Steve Jobs At Home In 1982 (digitaljournalist.org)
14. Steve Jobs and The Value of Saying No (betabeat.com)
15. The 313 Apple patents that list Steven P. Jobs among the group of inventors (nytimes.com)
16. Apple’s stock under Jobs: from $10 to $400 (cnn.com)
17. Daring Fireball: Steve Jobs Dies (daringfireball.net)
18. Steve Jobs: 1955–2011 (marco.org)
19. Steve Jobs, 1955 – 2011 (wired.com)
20. Statement by Apple’s Board of Directors (businesswire.com)
21. Bill Gates: “I Will Miss Steve Immensely” (allthingsd.com)
22. Steve Jobs Stanford Commencement Address: Death Is The Destination We All Share (immaturebusiness.com)
23. Obituary: Steve Jobs (economist.com)
24. BBC’s obituary for Steve Jobs (bbc.co.uk)
25. Barack Obama On Steve Jobs (allthingsd.com)
26. Tim Cook’s email to Apple employees about Steve’s passing (businesswire.com)
27. Thank You, Steve (laktek.com)
28. Larry Page on Steve Jobs (google.com)
29. “The way Steve Jobs described the computer—as a bicycle for the mind” (createdigitalmusic.com)
30. Steve Jobs: Thank you for the dream (dallarosa.tumblr.com)

I have not been an Apple user for a decade, but my programming career started when I was 14 with an old Macintosh Performa 450 and Hypercard. I guess a lot of what I am doing now would not have happened if not for Steve & Steve. How time flies.

Romania – Days 10 & 11

Where we slept in Sibiu.

As you might remember, we spent two nights at the Cocosul Rosu in Sibiu. On the whole, the stay was pretty pleasant, although the lack of a host-provided breakfast had us walk all the way to the town squares in search of a restaurant that would be open early enough to accomodate us (our final choice is Timi’s, in the southwest corner of the Piata Mare). Also, do not under any circumstances open the window past nightfall, or you will let in an entire menagerie of bloodsucking insects.

On day 10, we started with a quick visit to the Brukenthal museum of art. The exhibits were correct bordering on remarkable, but the maze-like layout of the museum (as with, it seems, all museums we’ve visited in Romania so far) is extremely frustrating. Indeed, navigating involves a fair bit of backtracking, and there are often several forks both within exhibitions and between exhibitions where you will require the assistance of a museum employee, because there are no useful signs or written hints available.

Brukenthal Museum of Art

Our next stop was Brașov. As an interesting bit of trivia, the old name of the city was Corona, and so the modern beer brand Corona lavishly sponsors the city pubs, bars and restaurant terraces.

Near the city is the pass of Bran, overlooked by the castle of Bran, the kind of castle Bram Stoker would have chosen for count Dracula to live in. The castle was renovated, its walls were painted white, and flowers were planted everywhere, so whatever eerie gothic aspect Stoker could have seen there is probably gone, but the peddlers of vampire-themed trinkets right outside the castle doors are there to stay.

Entrance to Bran castle.

A room inside Bran castle.

Secret door in the Bran castle library.

Empty corridor inside Bran castle.

Inside the Bran castle courtyard.

Bran castle is by all definitions a tourist trap. The roads that lead to the city are lined for miles with housing and restaurant advertising, and the city itself is drowned in far more traffic than its single road can allow. Everything here reaches prices beyond anything else in the country. The ice cream parlour in front of the castle serves ice cream that would be costly in a posh Parisian restaurant, though I have no reason to assume that it is actually worth it.

I am lucky to be two meters tall and be able to see above the heads of the hundreds of tourists navigating the (again, maze-like and frustrating) corridors of the castle, although the low ceiling in many of the rooms could prove quite unforgiving if you ever forget it’s there.

Our bed & breakfast in Brașov.

On day 11, we visited Brașov itself. Before I post pictures, here’s some information about the layout of the city: most of the interesting pieces are in a valley in the Carpathes, with the south edge of the valley holding a cable car station and the name “BRASOV” written on the top, Hollywood-style, and the north edge of the valley holding two fortified towers (the white tower and the black tower). Inside the valley is the Council Square (Piata Sfatului) and the Black Church.

The cable car and southern ridge, seen from the Council Square.

Our first trip of the day involved the cable car. The view was so gorgeous, we forgot to take good pictures of it.

Looking down through the letter B.

After we came back down, we visited the white and black towers.

White tower seen from the southern ridge.

Black tower.

Both towers contain museums. The Black tower museum was opened every day 9-6, and we arrived at around 1 pm, so the museum was obviously closed. I swear, all the museums we try to see are closed for unspecified or ridiculous reasons when we get there.

The White tower museum was open, and therefore much more amusing.

First, let it be known that the top floor of the White tower is the best sauna in the entire city, and that is probably unintentional. The top floor of the tower has a dark wooden floor and no ceiling (it burned down in the last city-wide fire) and so it is capped with an array of glass panels that turn it into a glasshouse of sorts. You can feel the heat wrapping from your scalp down to your toes as you climb the last flight of stairs, and five minutes later you can smell yourself roasting.

I Wish.

The public employee in the White tower is responsible for selling tickets, but also has a small shop of various souvenirs, trinkets, postcards, audio CDs, pamphlets and other things that she will try to sell at any occasion, with unerring insistence. She offered me, in no more than two minutes’ time, a presentation pamphlet of the White tower in French (which was actually Spanish) for 2 lei, an unfolding image book of the tower for 7 lei, two postcards for 3 lei, an audio CD about the region for 15 lei, and a small keychain trinket for 5 lei that I did not identify.

I wish I could sell my start-up product like that.

Mountain river below the White tower.

The Black Church.

The city is also home to the Black Church, so named because it was covered in soot after the aforementioned city-wide fire. The church contains several organs collected from surrounding churches in addition to its own beautiful 4000-pipe organ. We went to a concert in the evening, involving some quite elaborate Bach and Liszt pieces.

Romania – Days 8 & 9

On day 8, we drove from Târgu Jiu to Sibiu. Alix was driving for the first half, and I caught this on the side of the road:

A Stork

We stopped for what we expected to be a quick visit at the Hurez monastery near Horezu. There were many people, as August 15th is a religious celebration. While we were visiting, three ladies came up to me, handed me a camera and asked me to take a picture of them. I obliged. We met again near the cloister, where the sisters were giving out some sweets and wine, and the three of them invited us to have lunch with them in the monastery. We agreed.

Lunch was served in the two communal dining rooms of the monastery. We ate in the smaller of the two along with maybe a dozen other people, who were all quite interested in hearing about my Romanian roots and a comparison with French culture. The food was simple: vegetable ciorba, exceptionally tender veal with mashed potatoes, and watermelon.

We were then invited to visit the private areas of the monastery — as one of the three women knew the mother superior quite well — and we enjoyed some coffee, sweets and some slices of delicious telemea cow cheese produced at the monastery, while enjoying this view:

Looking south

We were also allowed to visit the bell tower:

Looking east

And we were also shown the private chapel where the Brâncoveanu family used to pray, when they lived in the monastery, as well as one of the first printed bibles written in Romanian.

We took our leave two hours and a half later than we had expected to, but with a better lunch that we could have hoped to find in Râmnicu Vîlcea. Still, this day brought us more than just free food: knowing that people are willingly and selflessly sharing with others, expecting nothing more than a few words in return; and that the best experience is not one you can buy.

Inside the Hurez monastery

The rest of the day was spent driving up the valley of the Olt river and reaching Sibiu.

Had this on my right for around 50 km

The Bridge of Lies, in Sibiu

We are spending two nights at the Cocosul Rosu bed and breakfast (I kid you not, this means the Red Cock Rooster) before going to Brasov.

Sibiu is a Romanian city with a strong german-speaking community, beautiful medieval architecture and a much better shape than other cities we have visited so far. If I had to pick, I’d rather have Sibiu than Bucharest.

On day nine, we visited the city. The Brukenthal museum of arts was closed, but should be open again tomorrow. Instead, we visited the Brukenthal museum of history (which had a quite enjoyable exhibition about the city guilds), then toured the city under a blistering heat and unforgiving sun.

The other name of Sibiu is Hermannstadt

East view from the clock tower

West view from the clock tower

Paper model of the (old parts of the) city

A street behind the fortified wall

A small medieval street

The orthodox church

Romania – Days 6 & 7

First, the eye candy. This is how day seven ended:

Coloana Infinitului

Coloana Infinitului

On day 6, we started from Drobeta Turnu Severin and rented a car up to Baile Herculane, nested in a valley in the mountains. There, we had a late lunch at the Hotel Ferdinand restaurant, which is beautifully laid out as a series of terraces on a fairly steep slope.

Hercules

Hercules

The hot mountain springs at Baile Herculane were already known by romans (hence the name), and are still active. We tried them out.

Left: cold. Right: hot.

Then, we visited the nearby Iron Gates, a beautiful gorge on the Danube river that separates Romania from Serbia. While driving along the Danube, I actually received a welcome SMS from the Serbian branch of my mobile provider…

Serbian side of the gorge.

The penultimate narrowing on the Danube.

Sadly, the Drobeta Turnu Severin museum was closed, which included the last standing parts of Emperor Traian’s bridge (the one Romans used to bring over enough troops to seize control over Dacia).

Closed for renovation.

Day seven started in Tîrgu Jiu, northeast of Drobeta Turnu Severin. We are staying at the Hotel Restaurant Europa, which happens to have a great restaurant with a great lemonade.

Demand to see life's manager!

We drove west from the city to explore Constantin Brâncuş’s home town of Hobiţa.

Museum Sign

Wooden church erected by Constantin's grandfather.

We pushed further west to Baia de Aramă, visiting the Tismana monastery along the way, where we were caught by rain in a forested valley.

Sun + Rain + Forest

Back in Târgu Jiu, we visited the scluptural ensemble by Constantin Brâncuş dedicated to the solders who died in the Great War. It is composed of the Table of Silence (twelve stone chairs around a large round stone table) followed closely by the Gate of the Kiss (a large stone gate), then the Path of Heroes (an empty path, about 1300 m long) and finally the Column of the Infinite.

The artist designed the Path of Heroes so that a visitor sitting at the Table of Silence and looking through the Gate of the Kiss would see the Column of the Infinite in the distance. This was planned in 1935-1938. However, in 1937, king Carol II authorized the building of an orthodox church in the middle of the Path of Heroes, completely breaking the perspective.

The picture at the top of the article is one of the Column of the Infinite.

My Hat of the Infinite

Romania – Days 4 & 5

Today is our last day in Bucharest this week. The weather was sunny again, so we visited outdoor locations.

Hipster graffiti on the National History Museum.

Vlad the Impaler

Grave of Mihail Eminescu

Grave inscription: 'You. I was what you are. You will be what I am.'

Carol I gardens

This annoys me to no end.

Quite scary. Does this really help sell kids' clothing?

We dined at the Caru cu Bere

The Caru cu Bere is a beautiful location. It’s also extremely loud and filled with cigarette smoke, and the food is not significantly better than other restaurants we sampled. As its name implies, it probably serves good beer, but I did not try.

Night train to Timisoara

The train left us off at the Timisoara station at 7:25 this morning. The trip was quite pleasent, albeit a bit cold.

Timisoara, Victory Square

Our older friend.

Timisoara, Union Square

Traffic lights have timers here. This is pure unadulterated genius.

Blue Dragonfly

Green Dragonfly

We actually witnessed a blue dragonfly saving another blue dragonfly from a green one.

The lawn is absolutely great here.

Staying at the Hotel Central

Romania – Day 3

We cannot seem to find tea — the local “Ceai” always seems to be some kind of fruit- or leaf-based infusion without actual tea, even though it is labeled as “Thé” or “Tea”. I have resorted to Pepsi for my morning caffeine.

We visited the Liceul Mihai Viteazul.

Mihai Viteazul, again.

We also visited the Palace of the Parliament - unofficially 'Casa Poporului'.

National Statistics Institute.

On the wall of the National Statistics Institute.

Dâmbovița, flowing through Bucharest.

National History Museum, beautiful pieces but dreadful setup.

We dined at the Monte Carlo in the Cişmigiu gardens. The food is absolutely excellent, and waiters are orders of magnitude more polite than the ones we have in Paris.

Surprisingly, the crippling heat of the last few weeks turned to freezing downpour tonight, but we managed to stay inside most of the time. In front of the National History Museum, a team of workers that were restoring the pavement did not work yesterday because of the heat, and did not work this afternoon because of the rain. I wonder whether the pavement will be done by the time we leave.

Romania – Day 2



We ate here yesterday night.



View on modern buildings from victory square.



Association of romanian writers.



The boring Goerge Enescu museum.



University of Industrial Chemistry.



Pepsi is the leading soda brand in Romania.



Coca-Cola is fighting for brand recognition here.



The crest of Bucharest.



An apartment from the communist era.



My old elementary school.



I used to play around these parts a lot.



Titan Metro Station



James Bond's conspicuous parking spot.



A street in eastern Bucharest.



Beautiful Park in midtown Bucharest.



Artificial waterfall that fascinated me as a child.



A tree-like cement bridge.



Bust of Romanian Poet Mihail Eminescu.



It is getting late, still a lot to see.



Meat management, apparently.

Romania – Day 1

Châtelet les Halles

Roissy - Aéroport Charles de Gaulle

Otopeni - Aeroport Henri Coanda

A Decentralized Dating Protocol

I’ve been wondering about how a decentralized dating protocol could be implemented.

Here’s the idea : Alice would love to date Bob, and Bob would also love to date Alice, but both of them are too shy to actually ask the other out. The good news is, Alice and Bob are the protagonists of almost every single cryptography protocol out there, and they naturally have asymmetric encryption keys. So, they resort to using the MAP (Mutual Attraction Protocol) to reveal whether they are interested in each other, but only if the feeling is indeed mutual.

An elementary implementation of the protocol could behave as such:

  1. Bob wishes to tell Alice about his feelings. He concatenates a fixed ILOVEYOU prefix and random suffix RAND, encrypts it with Alice’s public key APub, then with his private key BPriv, This creates the cipher BPriv(APub(ILOVEYOU || RAND)).
  2. He then publishes the cipher to a public location in a way that can be easily found by anyone looking for it — such as a database indexed by the public key of the uploader.
  3. Alice wishes to know whether Bob has feelings about her. She scours the public databases for any items matching Bob’s public key, and stumbles upon the aforementioned BPriv(APub(ILOVEYOU || RAND)) cipher.
  4. Shen then decrypts it with Bob’s public key, and uses her own private key to decrypt the result. She ends up with ILOVEYOU || RAND and determines, based on the presence of the initial ILOVEYOU that there’s indeed a love interest around.

The protocol is of course symmetrical: when you wish to express your interest, you should both publish it to the public database and look through that database for a reciprocal interest.

This version of MAP has the following interesting properties:

  • Only Bob can publish Bob’s feelings on the public database, because doing so requires encrypting them with Bob’s private key.
  • Only Alice can determine whether a given entry on the public database is about her, because doing so involves her own private key.

However, it assumes that Alice will only search for Bob’s message if she is herself interested in him. This is not necessarily true : Alice might be running some software that automatically searches through the public database for people who like her. This clearly violates the constraint that the feelings should only be revealed if they are indeed mutual — that, before Alice can determine whether Bob posted an “I’d date Alice” message, she must post an “I’d date Bob” message herself for Bob to read.

The question I am stuck on is, can these constraints be implemented without involving a trusted third party ?

Article image © Nattu — Flickr



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