Google Code Jam 2014 Qualifiers

Google Code Jam has always been a competition I have cherished, simply because the problems they post are brilliant and the closest to reality as compared to problems of other competitions. They’re always fun to read, disect & solve, more often than not, the solutions are reasonably trivial (especially for the qualifiers) yet extremely subtle & deceptive.

Today I want to share the solutions of 3 problems I was able to solve, the code should pretty much speak for itself because none of it is very complex.

  1. Magic Trick

    This one was the easiest of all, more of a warmup I suppose. Here’s the solution :

  2. Cookie Clicker Alpha

    Based on Cookie Clicker game developed by Orteil, this one was slightly trickier, and required a little bit of math. I solved it with a recursive algorithm first, then optimized it into an iterative one to pass for the large input. Here’s my solution with both recursive and iterative parts :

  3. Deceitful War

    This one was really subtle, easy enough to understand but hard to implement. It took me a while to put my understanding of how much being deceitful at the game called War translated to my points. Here too I solved both the normal game War and Deceitful War recursively first (it’s just easier to think recursively thanks to Lisp), then translated those to their iterative counterparts. Here is my solution with both recursive & iterative parts :

VIM Custom TabLine

Hi guys,

VIM allows has an option ‘tabline’ that one can use to configure how the tab line would look like. Back when I used to use gvim, I could very easily manipulate how the text on the tab looked like by setting the ‘guitablabel’ setting, however ‘tabline’ is not all that easy to configure.

Here is what I use now :

This is what it looks like : vim tabline

Creating Custom Scratch Buffers in VIM

The other day I wanted to open a scratch buffer to write some temporary code and the pass it on to a repl to test it out, the idea was that I could modify it as needed and resend it back to the repl and see the changes, helps to debug easily.

So I just wrote out this simple code here that allows me to launch a scratch buffer in different ways, but the difference is I can set various options for it while creating it. First lets have a look at the code :

Now this allows me to open a scratch buffer with various options, like I could call :Sedit ft=javascript and that would open a scratch buffer with filetype javascript (and hence show the right syntax highlighting). The cool part is all these options are set local to the buffer and can just be space separated to the command. The buffer will not be listed in :ls and after you :q it will be wiped out completely from vim. Couldn’t be any simpler!

VIM – Filter Quickfix List

If you are used to using the quickfix list in VIM there are times when you want to filter certain things out of the quickfix list to narrow it down to relevant results that you need. Rather than firing the quickfix command all over again with a refined expression, it is easier & often faster to simply remove items from the list. I wrote this simple vimscript to do just that.

Using the above now allows you to filter the quickfix list by calling :QFilter pattern. By default it filters the list to keep results matching the pattern but if you call it :QFilter! pattern. it will remove results that match the pattern.

VIM – Toggle Ruby Hash Syntax

Ruby 1.9 introduced a new json style ruby hash syntax. Although we can use this to define static hash objects and puts a limitation on the key we can use, it’s a fairly neat syntax nevertheless. However I work on several projects, both new and old and hence the new syntax is not always readily available.

To demonstrate the sheer power of regular expressions & VIM, here’s a tiny snippet that allows you to quickly toggle a ruby hash syntax from one form to other.

VIM for Multiple Projects in separate Tmux windows

My development environment setup consists of several tools, however the 2 most used and essential tools that have a great impact on my workflow are tmux & vim. Since I often work on several projects, I find it best to work on different vim sessions in separate tmux windows.

However tmux by default only shows the name of the currently running process in the title and that can often lead to confusion as to which tmux window is which project. To solve this issue I came up with a very simple vim script that utilizes tmux’s powerful API to automatically rename the tmux window appropriately and hence make it incredibly easy for me to know which tmux window is for which project.

Here is the vimscript, that you can put anywhere within your ~/.vimrc :

Here’s a screenshot of the same :
VIM for multiple projects within tmux

ActiveRecord like where for array of hashes in ruby

Edit : Updated the code as per the suggestions made by Masklinn.

Recently I was working on Issue#1 of my Soulmate Rails gem, which is a very simple and obvious optimization that I should have thought of myself. Thanks to lephyrius though for pointing it out. In my search method I was looping through the search results and calling find on each to get it from db. The fix involved to instead use a single where for all ids so that it translates to a single db call. A simple fix as well as an optimization.

However once I implemented it, I notice my tests were failing. On closer inspection i found they are failing because the models I created for testing using supermodel gem, didn’t have a where method. For a moment I thought WTF, and then I headed on to supermodel and looked through the source and to my surprise, it in fact did not implement a where method. So I took it upon myself to do it.

Here’s the generic code I wrote that could be applied to any array of hashes :

Now you can do

And you will get what you’d expect.

I updated supermodel in my fork to support such a where method and have sent the original author a pull request, hopefully it will get pulled soon.

All my tests pass now! Yay! I have released v0.3.0 of Soulmate Rails. Be sure to check it out.

PS : How about a code review ? Is this optimal or can it be improved further ? I’d like to hear thoughts from others.

VIM Markify

Recently I picked up some minor configs for ruby from Tim Pope’s vimrc. Here’s the code :

What this does is given the filetype is Ruby, it correctly sets up the compiler and makeprg such that it allows you to run your tests via :make! This is pretty neat I must say :), because it correctly loads the quickfix list with the errors and I can actually traverse them in order and fix them. All this without needing any plugin whatsoever :).

Ever since I started using this, I always wanted to mark the lines with errors / warnings with nice signs to highlight lines with errors instantly after I ran :make or :lmake, something similar to what Syntastic does but not just for syntax errors, actual test run errors. As I searched for similar plugins, although I found a bunch of them, I didn’t find them to be very intuitive or simple enough.

Hence I started exploring through vim’s help in an attempt to trying and understanding how I can tap into quickfix & location lists and process them. As it turns out, it’s quite simple and I ended up developing vim-markify overnight.

I’ve made it quite flexible and it works quite well with all quickfix commands – :make, :lmake, :grep, :lgrep, :grepadd, :lgrepadd, :vimgrep, :lvimgrep, :vimgrepadd, :lvimgrepadd, :helpgrep, :lhelpgrep, by tapping into the QuickFixCmdPost autocmd event which triggers right after you run any of the previously mentioned quickfix commands. Although you can choose to disable the autocmd by putting let g:markify_autocmd=0 in your vimrc so that it doesn’t do this automatically and you can trigger :Markify, :MarkifyClear or :MarkifyToggle commands or their corresponding mappings <Leader>mm, <Leader>mc or <Leader>M which can of course be changed. And I was able to achieve all this under 170 sloc :). A lot more things are configurable, I would encourage you to check :h markify.txt within vim or refer to the code at Github.


VIM Better FoldText

Update 3: Improved the code for extraction of fillchar from ‘fillchars’ option and taking ‘foldcolumn’ into account.

Update 2: Fixed the regex for removing the fold marker from the displayed text by splitting the ‘{{{‘ in the regex to ‘{{‘. ‘{‘ so that it is not treated as a fold marker by vim. Thanks to Amadan on reddit here.

Update: Fixed ‘NeatFoldText()’ to get foldchar from ‘fillchars’ settings.

Initially when I started using VIM, I had borrowed configs from my mentor Vagmi Mudumbai (to whom I am eternally thankful!!!).

He used folding in VIM actively. I on the other hand though, barely got around using VIM itself, found folding to be quite confusing and hard to work with. The first folding mapping I learnt was ‘zR’, which is for recursively opening all folds in the current documents, so I don’t have to deal / worry about them. I became so habitual to using ‘zR’ that one day I decided I was better off without folding altogether, after all I was clearly not using folding anyways. That day I removed folding related configs from my ~/.vimrc. Much later as I became more comfortable using VIM, I came back to folding and have not looked back ever since!

I have always thought though that the vim’s default folding look and feel could use some beautification, and although I have been aware about ‘foldtext’, I never really got around to understanding how to take advantage of it to customize things like I wanted.

After quite a bit of effort and quite a few iterations, I now present to you my ‘NeatFoldText()’, a vim function that makes the fold line look really impressive, meaningful and neat at the same time! It puts focus on what’s most important (the text in the start of the fold). And right aligns the number of lines in the fold. Also formats it to fixed size which makes it look neat and consistent.

Put this in your $VIMRC (~/.vimrc) :

And this is how the fold text look like :


This example should also prove to be a great starting point / example for those who wish to tweak the folding text further.

VIM Table Mode

UPDATE 2: Released v 2.0 of the plugin. Check github for details.

UPDATE : I have added more features to the original plugin, showcasing some core features in a new demo (Part 2).

Recently a friend of mine showed off emacs table mode to me and to be honest I felt a bit jealous :). Hence I began to search for existing vim plugins that might offer a similar functionality and I did find a plugin vim rst tables, which is a ftplugin that aids the creation of tables within rst files and allows you to format existing content into a table, although this plugin came closest to what I was looking for it wasn’t quite there. Then I found a very interesting & simple plugin shared as a gist by the infamous Tim Popecucumbertables.vim which I found quite impressive.

I began experimenting with this in an attempt to make it a bit more comprehensive and to allow for better formatted tables creation and after hacking on it for a couple of nights I came up with the table-mode vim plugin.
Read More →