Thursday, June 21, 2012

Google Code Jam in Scala : Speaking in Tounges

Part One of the series "let's solve Google Code Jam problems in Scala, without ever using the keyword var".

The first problem for the 2012 qualification round gives you the task of "implement a monoalphabetic substitution cipher if you have access to sufficient plaintext/ciphertext". At the bottom of the problem description you have a nice seed data, which you can put in a map:

val stringMap = Map(
  "ejp mysljylc kd kxveddknmc re jsicpdrysi"
         -> "our language is impossible to understand",
  "rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"
         -> "there are twenty six factorial possibilities",
  "de kr kd eoya kw aej tysr re ujdr lkgc jv"
         -> "so it is okay if you want to just give up"
)
This is a string-to-string map. But you need a character-to-character map. Converting to that is easy, you just have to know some facts about the scala collections:

  1. every map can be seen as a sequence of (key,value) pairs - you can iterate over them
  2. a string is also a Seq[Char], and as such, it has a zip method. So if you zip two strings together, you get a sequence of character pairs
  3. the reverse of (1), thus if you have a sequence of (key,value) pairs, you can create a map
val charMap = for(
    (keyString,valueString) <- stringMap;
    (key,value) <- keyString zip valueString)
  yield (key,value)

Since stringMap is of type Map[String,String], due to the clever scala mapping system, the type of charMap will be Map[Char,Char].
Now we can create our cipher decode function, and test it out. For this, I'm giving you a few different solutions, that are equivalent, as the differences are only syntactic sugar:
def decode(s:String) = for(c<-s) yield charMap(c)
def decode(s:String) = s.map(c=>charMap(c))
def decode(s:String) = s.map(charMap(_))
println(decode("rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"))
"there are twenty six factorial possibilities"
Before you download the first input file to solve, you might ask one question: "I know map throws an exception for unknown keys. What if the sample we have so far doesn't cover all letters of the alphabet?" Good question. Let's ask our code for the answer! Again the extremely versatile collection classes come to the rescue:

  1. you can use the magic keyword "to" to create a NumericRange, and it works for all numeric types, including Char
  2. basically every collection has a toSet method, that creates an immutable set
  3. sets have a substitution operation "--" that can remove from a set anything that can be iterated over
  4. maps have methods to get the keys and the values as Iterables
val alphabet = ('a' to 'z').toSet
println(alphabet -- charMap.keys)
Set(q, z)
println(alphabet -- charMap.values)
Set(q, z)
Oops, there are two characters that don't have a mapping. Fortunately, if you read the beggining of the problem, there are some hints...

Sunday, January 31, 2010

Panasonic SA-PT860

We got this DVD player for our wedding. It can play AVI files, but unfortunately is very picky in what it accepts. And it happily re-scales the movies. Either crops part of it, so parts of the screen are missing, or puts nice little black bars on the side or on the top.
At last I got some of it working. This is how you can convert an 16:9 aspect ratio home video to a format that looks right:

mencoder original.avi -ovc lavc -lavcopts vcodec=msmpeg4 -oac mp3lame -lameopts cbr:br=128 -vf scale=660:350 -lavcopts vbitrate=2000:aspect=16/9 -sub subtitles.srt -o panasonic.avi

Thursday, April 10, 2008

“Adium” is an application which was downloaded from the Internet. Are you sure you want to open it?

I'm regretting choosing Mac as my laptop at Google. I thought it would be cool to learn something else than Linux. I thought it would be a nice to see that famous user friendliness. Instead, I get this annoying message about Adium, that is part of the company default image. And the only way to remove it is opening the command line, and typing:

find /Applications/Adium.app/ -print0 | sudo xargs -0 xattr -d com.apple.quarantine

Is this the new, fancy Mac? I feel right back home. And ten years younger.

Monday, March 3, 2008

NoMachine NX and the ctrl key problem

I thought I give it a try. I mean, why should I develop on my machine when I could do it on the server farm?

But the ctrl key didn't work. When I pressed Ctrl-l in xterm, it just printed an "l", instead of resetting. Usually, it means xmodmap problems. But this was between Ubuntu boxen. A quick run with xev showed, that Ctrl-l did for key events: l-down, l-up, ctrl-down, ctrl-up. So it did get the key, it just delayed it somehow, until I released the l key.

The solution?

System/Preferences/Mouse/Pointers, and uncheck "Highlight the pointer when you press Ctrl"

Sunday, April 8, 2007

Ditching PC Suite

Since I'm leaving Nokia, my first step will be to install Ubuntu on my laptop. Unfortunately this will mean I won't be able to run PC Suite.

Since this was the way I backed up my contact list from my N71, and I also used it to sync with Outlook, I was kinda afraid.

But, while we are at it, I won't be using Outlook, either... Google Calendar is the way to go. And goosync seems to be perfectly capable of syncing with my phone. For additional coolness points, it is able to do this without actually asking me for my google account or password. What the Liberty Alliance Project tried (and failed) to do 5 years ago, Google just went ahead and did.

For backing up the contacts... have a look at ZYB. They have syncml-based backup system, for free. I don't really see their business model, yet. Seems they wanna make money off on things like outlook and iPod synchronization.

Saturday, March 31, 2007

reversing a long

This is the other question I was asked. The straightforward method: loop 64 times, shift out from right, shift in from left. This means 128 shift operations, and 64 ANDs, 64 ORs.

My brain, of course, wouldn't let go, so I came up with something much more elegant, somewhere, half asleep on the plane:

public static final long reverse(long l) {
l = (l>>32)|(l<<32);
l = ((l>>16)&0x0000ffff0000ffffl)|((l<<16)&0xffff0000ffff0000l);
l = ((l>>8)&0x00ff00ff00ff00ffl)|((l<<8)&0xff00ff00ff00ff00l);
l = ((l>>4)&0x0f0f0f0f0f0f0f0fl)|((l<<4)&0xf0f0f0f0f0f0f0f0l);
l = ((l>>2)&0x3333333333333333l)|((l<<2)&0xccccccccccccccccl);
l = ((l>>1)&0x5555555555555555l)|((l<<1)&0xaaaaaaaaaaaaaaaal);
return l;
}


This is 12 shifts, 10 ANDs, 6 ORs.

parity

I got the question, of how do you compute the parity of an int? My first reaction was that, well, you make a loop, 32 times, shift right, and do an xor on the least significant bit. I mean, man, that is an easy question, why do you even ask?

I'm ashamed to say, that I should have thought more carefully. I woke up in the middle of the night, 8 hours later, and had a relevation:


public static final int parity(int i) {
i = (i>>16)^i;
i = (i>>8)^i;
i = (i>>4)^i;
i = (i>>2)^i;
i = (i>>1)^i;
return i&1;
}