Wednesday, January 8, 2014

Arch + XMonad / GNOME on MacBook Pro Retina 11,1 (13-inch, late 2013)

For the past few months, I've tried running OS X as my main OS on my MacBook Pro Retina (late 2013). I eventually got tired of it, so a week ago I started trying to figure out how to dual boot Arch on this machine. This is a log of the steps that had to go through. (Before doing this, I reset OS X via the recovery partition, so this is a clean install.) The following additional pages may be helpful as reference:

I'm assuming that the reader has some basic level of familiarity with Linux and can understand most of what I'm doing (or look it up if need be). If anyone has any updates or helpful info, feel free to email me and/or comment below, and I will update the guide accordingly.

Boot disk

In OS X, download the standard Arch install ISO and run
dd if=arch.iso of=/dev/sdX
to create the boot disk.

Bootloader

We will use rEFInd because it seems slightly easier than hooking up GRUB to EFI. In OS X, download the rEFInd package and run
sudo ./install.sh --alldrivers
Edit /EFI/refind/refind.conf and enable the scan_all_linux_kernels option. (I also enabled textonly mode because I thought the GUI looked tacky.) In the folder /EFI/refind/drivers_x64, remove all the drivers except the one for EXT4. (Not sure if the last step is necessary -- can someone confirm?)

Partitioning, Part 1

While still in OS X, use the partition manager to resize your OS X partition. I left it with 50 GB, but this is up to personal preference. Note that OS X actually has 3 partitions (EFI boot partition, main partition, recovery partition), but it only shows you one of them.

Internet

Boot into your Arch live USB (rEFInd should be able to detect it automatically). You need an internet connection to install the base system. I used USB tethering via an Android phone, but other options may work as well.

Partitioning, Part 2

Use cgdisk /dev/sda to set up / on /dev/sda4 and /home on /dev/sda5. Then run
mkfs.ext4 /dev/sda4
mkfs.ext4 /dev/sda5
mount /dev/sda4 /mnt
mkdir /mnt/home && mount /dev/sda5 /mnt/home
to create new EXT4 file systems on those partitions and mount them.

Base System / Partitions, Part 3

Run the following to set up the base system and fstab:
pacstrap /mnt base base-devel
genfstab /mnt >> /mnt/etc/fstab
At this step we have a basic working Linux system that you can chroot or reboot into:
arch-chroot /mnt /bin/bash

SSD Performance issues

We should edit /etc/fstab to improve SSD performance:
/dev/sda4   /       ext4    defaults,noatime,discard    0 1
/dev/sda5   /home   ext4    defaults,noatime,discard    0 2
The default boot options may cause the SSD to hang. Add the following line to /boot/refind_linux.conf to prevent this:
"Default" "ro root=/dev/sda4 libata.force=noncq"

Keyboard / Locale / Time

echo "somehostname" > /etc/hostname

# set up keyboard layout and system locale
echo "KEYMAP=dvorak" > /etc/vconsole.conf
vi /etc/locale.gen # uncomment what you want
locale-gen
echo "LANG=en_US.UTF-8" > /etc/locale.conf

# set local time and set hardware clock to UTC
ln -s /usr/share/zoneinfo/US/Pacific /etc/localtime
hwclock --systohc --utc

Users

# set root password
passwd

# add user
useradd -m -g users -G wheel -s /bin/bash someusername
passwd someusername
visudo # uncomment wheel
One last thing -- we should set up wifi before rebooting and logging in to the new account.

Yaourt, Wifi

Follow the instructions here to get yaourt. Then use it to install broadcom-wl from the AUR to get wifi drivers:
yaourt -S broadcom-wl
I like to manage my connection with wicd so I'll get that as well:
pacman -S wicd
systemctl enable wicd.service
Now we can reboot and start playing around with the system!

XMonad with GNOME

Normally I would forgo GNOME, but they currently have (as far as I know) the best solution to solving the high-DPI scaling issue. Grab the following packages:
pacman -S xorg-server xorg-xinit xorg-server-utils xf86-video-intel xf86-input-synaptics \
          gnome-session gnome-settings-daemon
yaourt -S xmonad-darcs xmonad-contrib-darcs
Then follow the instructions from my previous post to make XMonad and GNOME play nicely with each other.

Additional steps / troubleshooting

The above steps will get a minimal working setup on your Retina Macbook Pro. However, there are still a lot of useful things you could configure to make your life easier:

Firefox

Change layout.css.devPixelsPerPx to 2 to make it scale everything up for the retina display.

Missing Cursor

Try running
gsettings set org.gnome.settings-daemon.plugins.cursor active false

USB Automounting

udiskie is a simple daemon to automount disks with very few dependencies, which is great for a minimal setup.

Fonts

OS X ships with some great built-in fonts. I strongly recommend grabbing their fonts from these directories on your OS X install and copying them over to Linux.

Tuesday, January 7, 2014

Linux, retina / high-density displays, and external monitors

The issue

Currently most Linux desktop environments work rather poorly with high-density displays, and require a lot of manual tweaking. Recently, GNOME 3 added support for high-density displays, so the UI should automatically rescale itself properly for GNOME versions 3.10 and higher. Unfortunately, there's one slight issue: If you connect an external monitor, the text and icons are massive. This is because (as far as I know) GTK, X, and much of the substrata of renderers underlying the GUI only support a global DPI or scale setting for all monitors.

Workaround

However, there is (sort of) a workaround. We can manually rescale so that the the external monitor is correct, but the retina monitor has small text. (Presumably if you are using an external monitor, then your laptop monitor is not your main work monitor.) In this patch, we see that GNOME rescales windows based on the parameter scaling-factor in schema org.gnome.desktop.interface. Thus, all we have to do to manually set the scale factor is to run
gsettings set org.gnome.desktop.interface scaling-factor X
where X is 1 or 2, depending on how we want pixels to be normal-sized or enlarged. (If X is 0, then GNOME decides for you, but this may or may not be what you want.) For expedience, you can attach a hotkey to these commands, or you can detect xrandr events and rescale automatically.

Required packages

It turns out that only a very minimal set of packages need to be installed for this to work -- gnome-session and gnome-settings-daemon, at least version 3.10 or higher. Because of the sparse requirements, this can be adapted to work for all GTK applications in lightweight desktop environments / window managers (e.g. XMonad or awesome) so long as you start them via a minimal GNOME session. I also strongly recommend building xmonad-darcs and xmonad-contrib-darcs from the AUR because of a bug (see edit below).

Minimal .xinitrc + XMonad + GNOME example

A minimal way to get the above method working involves creating the following files:
~/.local/share/applications/xmonad.desktop:
[Desktop Entry]
Type=Application
Name=Xmonad
Exec=xmonad
NoDisplay=true
X-GNOME-WMName=XMonad
X-GNOME-Autostart-Phase=WindowManager
X-GNOME-Provides=windowmanager

~/.config/gnome-session/sessions/xmonad.session:
[GNOME Session]
Name=Xmonad/GNOME
RequiredComponents=gnome-settings-daemon;xmonad
Make sure you use gnomeConfig in your xmonad.hs. Then end your ~/.xinitrc with
exec gnome-session --session=xmonad
This will execute a minimal GNOME session instance which only runs gnome-settings-daemon, xmonad, and almost nothing else.

Edit (2014-07-16): With the latest version of D-Bus and with XMonad 0.11, gnomeConfig from XMonad.Config.Gnome doesn't properly register XMonad to GNOME, so you'll see a GNOME error dialog upon starting your XMonad-Gnome session. This has been fixed in XMonad-Contrib 0.12 from the AUR.

Monday, November 4, 2013

Mid-Atlantic Regional ACM Programming Contest 2013, problem F

In the Mid-Atlantic Regional ACM Programming Contest this year, one of the more interesting problems was the following:

Suppose there are \( N \leq 10^5 \) stars such that star \( i \) has coordinates \( x_i, y_i, z_i \), where \( |x_i|, |y_i|, |z_i| \leq 10^9 \). Given \( K \leq 10^9 \), count the number of pairs of stars which are within distance \( K \) from each other. The cluster of stars is sparse -- that is, there are at most \( M = 10^5 \) pairs of stars within \( K \) of each other.

One simple solution is to think about partitioning the space up into cubes of side length \( K \). Then, for each star, it suffices to check the number of stars in the same cube and adjacent cubes and see whether they're within \( K \). Surprisingly enough, this actually runs in \( O(M) \) operations.

First we consider the case where space is one-dimensional, and our cubes are just intervals of length \( K \). Let the intervals contain \( a_1, a_2, \ldots, a_n \) elements. Note that two stars within the same interval are guaranteed to be within \( K \) of each other. Thus, \[\sum_{i=1}^n a_i^2 \leq M\] What is the number of operations that this will take? Well, for each star in interval \(i\), we examine all stars in intervals \(i - 1\), \(i\), and \(i + 1\). This is just \[\sum_{i=1}^n a_i (a_{i-1} + a_i + a_{i+1})\] Note that the \(a_i^2\) terms are \(\leq M\); furthermore, the \(a_ia_{i-1}\) terms and the \(a_ia_{i+1}\) terms are symmetric. Thus, it suffices to show that \[\sum_{i=1}^n a_i a_{i-1} \leq M\] Here we apply something known as the rearrangement inequality*, which roughly says that if you have two sequences of numbers \(x_i\) and \(y_i\), and you want to rearrange the \(x_i\) and \(y_i\) to maximise \(\sum_i x_i y_i\), then it's best to rearrange them in ascending order. In this case, our sequences are \(a_i\) and \(a_{i-1}\), and the sequences in ascending order is just \(\sum_{i=1}^n a_i^2\), which we already showed was \(\leq M\). This means that the whole algorithm takes \[\sum_{i=1}^n a_i (a_{i-1} + a_i + a_{i+1}) \leq 3 M\]

The same argument can be extended to cubes -- however, in order to guarantee that \( \sum_{i=1}^n a_i^2 \leq M \), we need to make our cubes be of size \(K / \sqrt3\) so that all points within them are guaranteed to be at most \(K\) from each other. This implies that if we instead use cubes of size \(K\), then \(\sum_{i=1}^n a_i^2 \leq 3^3 M\). We can then apply the rearrangement argument as before, except with \(27\) adjacent cubes instead of \(3\). This gives us an algorithm which runs in \(729 M\).

In general, for dimension \(D\) we'll need \((3D)^DM\) operations for the same algorithm, so in high dimensions we'd likely need to exploit other tricks, like the fact that the volume of an \(n\)-ball disappears as \(n\) increases. We could then (maybe?) approximate the sphere with small cubes of size \(\epsilon K\) instead of simply summing over \(3^D\) adjacent, larger cubes of size \(K\).

* -- You could also prove this using Cauchy-Schwarz or some other famous inequality. Rearrangement just happened to be the first one I thought of.

Friday, October 25, 2013

TopCoder SRM 595 Editorial

Overview

Fewer people showed up for this SRM than usual, possibly because it was between 12AM and 5AM in most of Europe. I haven't yet looked at the Div 2 problems, but the Div 1 medium and hard problems were easier than usual.

LittleElephantAndIntervalsDiv1

Whenever a ball is painted, it is completely repainted; therefore, its final colour depends only on the final colour chosen to paint it. Define \(s_i\) as the last stage which paints ball \(i\), or \(0\) if no stage ever paints ball \(i\). Then our solution is just \(2^N\), where \(N = |\{s_1, s_2, \ldots, s_M\} \setminus \{0\}|\).

LittleElephantAndRGB

This is one of those problems where there is an obvious but inefficient way to compute the solution (simply enumerating all tuples and checking in \(O(N^5)\) time, where \(N\) is the length of the string); thus the challenge is simply to optimise the solution so that it runs in time. In this case \(N \leq 2500\), so an \(O(N^2)\) solution should work.

Since we are looking for count pairs of two disjoint intervals and all intervals can be enumerated in \(O(N^2)\), then a natural solution to consider is to break the problem into two parts. The first part counts the number of first intervals in \(O(N^2)\), and the second part counts the number of second intervals in \(O(N^2)\) as well. As it turns out, this decomposition is sufficient to solve the problem.

For each nice \((a, b, c, d)\) tuple, either

  • \(S[a\ldots b]\) is nice
  • \(S[c\ldots d]\) is nice
  • or finally, there is some sequence of \(m\) Gs which spans both intervals (where \(m\) is minGreen)
Now suppose we want to iterate over all choices of \((c, d)\). (This is the second part of the decomposition.) If \(S[c\ldots d]\) is nice, then we're done. Otherwise, there must be some sequence of Gs which starts at the end of \(S[a\ldots b]\) and ends at the beginning of \(S[c\ldots d]\). In particular, if \(S[c\ldots d]\) has a prefix of \(g\) Gs, then \(S[a\ldots b]\) must have a suffix of at least \(m - g\) Gs. (If \(S[c\ldots d]\) is nice, we adopt the convention that \(g = m\).)

This suggests that the first part of the decomposition is computing \(count(b, g)\), the number of subsequences which end before \(b\) and has a suffix of at least \(g\) Gs (or is nice). Then our answer is just \[\sum_{c, d} count(b, m - prefixLength(c, d))\] where \(prefixLength(c, d)\) is the number of Gs at the beginning of \(S[c\ldots d]\), or \(need\) if \(S[c\ldots d]\) is nice.

In this case, it suffices to compute the number of subsequences which end at exactly \(b\) and have a suffix of exactly \(g\) Gs. Call this \(count'(b, g)\); then we can generate \(count\) from \(count'\) by just doing partial sums. To compute \(count'\), we can simply enumerate over all possible \((a, b)\) in \(O(N^2)\) time.

Note that there are some additional bookkeeping details (i.e. how to keep track of prefix and suffix lengths), but I'll leave those up to the reader.

Constellation

As with many problems involving expected value, one should immediately jump to thinking about linearity of expectation. This means that we should try to decompose the expected value of the area as a sum of some other variables; one possible way is as follows: \[A = \sum_{r\in R} I_r A_r\] where \(R\) is the set of all subregions of the polygon, \(A_r\) is the area of subregion, \(I_r\) is a binary variable indicating whether \(r\) is present or not. Then the expected area is just \[\mathbb{E}(A) = \mathbb{E}\left[\sum_{r\in R} I_r A_r\right] = \sum_{r\in R} P_r A_r\] where \(P_r\) is the expected value of \(I_r\), which is the probability of \(r\) being present. Note that I haven't quite defined what a subregion is -- that turns out to be the hard part of this problem.

It's tempting to try to decompose the area into triangles whose vertices are stars in the constellation, and then sum up the expected area of the triangles. Unfortunately, this doesn't quite work. Consider the second example -- there are 4 separate triangles, but each triangle intersects 2 other triangles. As a result, we overcount the area when all the triangles are present. Thus, the expected value of the area is too large.

One way to see the solution is to have a good understanding of the polygon area algorithm, AKA shoelace formula. This formula computes the area of a polygon in a clever way: first, we take each pair of adjacent points on the convex hull \((i, j)\) and extend them to a triangle by including the origin, \(o\). We then sum up the signed areas of the \((i, j, o)\)s -- which is positive or negative depending on whether \((i,j,o)\) are in clockwise or counterclockwise order. This can be done elegantly with cross products -- the area of triangle \((i, j, o)\) is just \((x_i y_j - x_j y_i)/2\). The expected signed area of the triangle is then its area multiplied by the probability that edge \((i, j)\) will be on the convex hull of the polygon.

\((i, j)\) is on the convex hull if and only if there is at least one visible star on the right side of \((i, j)\), and no visible stars on the left side. Again, we can use cross products to determine whether a point is on the left or right of \((i, j)\) -- if \((j - i) \times (k - i)\) is positive, then \(k\) is on the right; if it's negative, it's on the left side. Thus, the probability that \((i, j)\) is on the convex hull is just \[p_{i,j} = \left[\prod_{k \in L} (1 - p_k)\right] \left[1 - \prod_{k \in R} (1 - p_k)\right]\] Lastly, there is one additional case -- if there is some point \(k\) such that \(j\) is between \(i\) and \(k\), then \((i, k, o)\) contains \((i, j, o)\). In this case we'll overcount triangles again. The way to solve this is to consider \(k\) to be on the 'left' side; thus, whenever \(k\) appears, we won't add \((i, j, o)\) to our total. This gives us the following definitions of \(L\) and \(R\): \[L = \{k \mid (j - i) \times (k - i) < 0 \text{ or } k \text{ outside and colinear to } i, j\}\] \[R = \{k \mid (j - i) \times (k - i) > 0\}\] Then we can use \(p_{i,j}\) as before, along with the signed area, to compute the expected area of the polygon.

Pseudocode for the solution is then as follows:

  1. For all points \(i\) and \(j\):
    1. Let \(L = \{k \mid (j - i) \times (k - i) < 0 \text{ or } k \text{ outside and colinear to } i, j\}\)
    2. Let \(R = \{k \mid (j - i) \times (k - i) > 0\}\)
    3. \(ans \leftarrow ans + p_i \cdot p_j \cdot \left[\prod_{k \in L} (1 - p_k)\right] \cdot \left[1 - \prod_{k \in R} (1 - p_k)\right] \cdot (i \times j) / 2\)
  2. Return \(ans\)

Sunday, October 13, 2013

TopCoder SRM 591 Editorial: PyramidSequences

PyramidSequences

First, fix some \( n \) and \( m \). We begin by looking at an easier problem: If instead of looking at sequences of the form \( 1, 2, \ldots, n - 1, n, n - 1, \ldots, 3, 2 \), what if all the sequence elements were distinct (e.g. if the sequence was of the form \( 1, 2, \ldots, 2 n - 2 \))? The Chinese remainder theorem guarantees that a number \( x \) from the \( n \)-sequence will be paired with a number \( y \) from the \( m \)-sequence if and only if \( x \equiv y \pmod{2g} \), where \( g = \gcd( n - 1, m - 1 ) \). We can partition the \( n \)- and \( m \)-sequences into equivalence classes modulo \( 2g \); each class contains \( (n - 1) / g \) or \( (m - 1) / g \) elements, so there are \( (n - 1) (m - 1) / g^2 \) pairings per class, or \( (n - 1) (m - 1) / g^2 \), or \( 2 (n - 1) (m - 1) / g \) unique pairings.

Unfortunately, the pairings are not unique. Each \( k \) in the \( n \)-sequence has two possible indices modulo \( 2 g \): \( \{ k \% (2 g) \) and \( (2 n - k) \% (2 g) \} \). Let us first consider the two indices are equal, i.e. \( k \equiv (2 n - k) \pmod{2g} \). Simplifying, this gives us \( k \equiv n \pmod g \). Since \( g \) is a multiple of \( n - 1 \), then \( n \equiv 1 \pmod g \), so our final expression is \( k \equiv 1 \pmod g \); i.e. \( k \equiv 1 \text{ or } g + 1 \pmod{2g} \). Note that this condition is independent of \( n \) or \( m \), so it suffices to simply find the number of \( k \) equivalent to \( 1 \) or \( g + 1 \) modulo \( 2g \) in each sequence and multiply the counts accordingly.

Now consider the case in which \( k \) has two distinct indices, \( k \% (2 g) \) and \( (2 n - k) \% (2 g) \). Again, since \( n \equiv 1 \pmod g \), the second index can be written \( (2 - k) \% (2 g) \). If \( k \% (2 g) \in [2, g] \), then \( (2 - k) \% (2 g) \in [g + 2, 2g] \) and vice versa. Thus, each \( k \) appears exactly once in the range \( [2, g] \) and exactly once in \( [g + 2, 2g] \). It suffices, then, to compute the result for one range. This is simply \( (g - 1) (n - 1) (m - 1) / g^2 \).

Putting the two cases (\( k \equiv 1 \pmod g \) or not) together, we have the following Python code. Some care must be taken to account for the special cases \( 1 \), \( n \), and \( m \).

from fractions import *

class PyramidSequences(object):
 def distinctPairs(self, n, m):
  g = gcd(n - 1, m - 1)
  an, am = [(x - 1) / g for x in n, m]
  bn, bm = [x / 2 + 1 for x in [an, am]]
  cn, cm = [x / 2 + (x % 2) for x in [an, am]]
  return (g - 1) * an * am + bn * bm + cn * cm

Sunday, December 9, 2012

TopCoder SRM 563 Editorial

Overview

This SRM featured three pairs of problems with easy and hard versions: FoxHandle, CoinsGame, and SpellCards. The two CoinsGame problems could be solved with graph search, and the two SpellCards problems could be solved with dynamic programming. Notably, the harder version of SpellCards reduced to a trivial application of knapsack, but proving this reduction was tricky and most coders used a more obvious, but longer, dynamic programming solution to solve it. In fact, the author himself stated in this forum post that he did not know about the knapsack solution until after the contest.

FoxAndHandleEasy

This is a useful exercise in using the substr() function. Let \( n \) be the length of \( s \). Iterate over all length-\( n \) substrings of \( t \). Let this substring be called \( u \). If \( u \) is equal to \( s \) and if the string formed by removing \( u \) from \( t \) is also equal to \( s \), then return true.

CoinsGameEasy

There are several approaches which work. The simplest one is probably just to brute force all possible moves. The following is pseudocode for a recursive solution which implements that idea:

// xi, yi are the coordinates of coin i.
// steps is the number of steps the number of moves that we have made so far.
rec( x0, y0, x1, y1, steps )
{
  if( ( x0', y0' is off the grid ) && ( x1', y1' is off the grid ) )
    return INFINITY;

  if( ( x0', y0' is off the grid ) || ( x1', y1' is off the grid ) )
    return steps;

  if( steps == 10 ) return INFINITY;

  ans = INFINITY;
  for each direction d
    let x0', y0' = move in direction d from x0, y0;
    let x1', y1' = move in direction d from x1, y1;
    ans = min( ans, rec( x0', y0', x1', y1', steps + 1 ) );

  return ans;
}
The recursion depth is at most 10, and each recursive call branches 4 times, so the function is called at most \( 4^{10} \approx 1 \text{ million } \) times. This is fast enough to pass on TopCoder.

Alternatively, you could use breadth-first search or some more fancy algorithms, but they aren't necessary in this case.

SpellCardsEasy

Let's start with a simple solution, figure out why it doesn't work, and then improve on it. Suppose we have the following recurrence:

f( i )
{
  if( i == n ) return 0;

  // use card
  use = 0;
  if( i + lvl[i] <= n ) ans = dmg[i] + f( i + lvl[i] );

  // don't use card
  no_use = f( i + 1 );

  return max( use, no_use );
}
This seems simple enough: We look at each card \( i \) and decide whether to use it or not. If we use it, then we remove cards \( i, i + 1, \ldots, i + lvl_i - 1 \), and then recursively proceed from there. The problem, unfortunately, is that the cards we decide to remove may not necessarily be contiguous. Consider the following example: \[ lvl = [ 2, 1, 1 ] \\ dmg = [ 100, 1, 0 ] \] Here it's optimal to first use middle card, then use the first card, dealing a total of 101 damage. Our algorithm, on the other hand, would return 100 because it uses the first card, and then discards the first two cards.

Suppose we keep a count of cards that need to be removed, but we don't remove them right away*. Call this value \( need \). Now, examining each card from left to right, we can do the following:

  • Don't use the card. This decreases our current \( need \) value by 1.
  • Use the card. This increases the damage we do by \( dmg_i \) and increases \( need \) by \( lvl_i \).

Claim: If, after examining all the cards, we have \( need = 0 \), then the cards we chose to use are a valid combination.

Proof: Suppose the rightmost card that we decided to use was card \( i \). When we processed card \( i \), \( need = k \) for some \( k \), and afterwards, we had \( need = k + lvl_i \). Since we managed to decrement \( need \) to 0 by the time we processed all the cards, then there must be at least \( k + lvl_i - 1 \) cards to the right of \( i \). Now let's use card \( i \) and then remove cards \( i, i + 1, \ldots, i + lvl_i - 1 \) from the deck. This new deck also satisfies the \( need = 0 \) property. That is, if you look at all the cards we decided to use and increment or decrement \( need \), then you still get to \( need = 0 \) after examining all the cards. We can then inductively apply the above process. Use the rightmost card, and then remove it, along with some cards to the right of it. Eventually we will have used all the cards we chose originally without breaking any rules of the game.

Based on our above observation, we can write a new recurrence relation:

f( i, need )
{
  if( i == n ) return 0;

  // use card i
  use = 0;
  if( need + lvl[i] <= n ) use = dmg[i] + f( i + 1, need + lvl[i] - 1 );

  // don't use card i
  no_use = f( i + 1, max( need - 1, 0 ) )

  return max( use, no_use )
}
Now we just need to use dynamic programming or memoisation to make sure that each recursive call gets evaluated at most once. The complexity of this algorithm is \( O( N^2 ) \) for \( N \) cards, which is more than fast enough for the time limit.

FoxAndHandle

There are several approaches to solve this problem. In this tutorial, I'll go over a simple semi-greedy approach. In general, problems that require a 'lexicographically least' solution suggest some sort of smart greedy solution, but this is not always the case.

We begin with a simple algorithm and fill in the blanks. The algorithm below keeps track of the position of the last character we used, and at each step, searches all subsequent characters and picks the 'best' one:

f( s )
{
  ans = "";
  last = 0;
  for t from 0 to length(s) / 2
  {
    best = last;

    for i from last to length(s)
      if (we can append s[i] to ans) && (s[i] < s[best])
        best = i;

    ans += s[best];
    last = best;
  }
}

The only missing piece is determining whether, at each step, we can append some \( s_i \) to \( ans \). As it turns out, the following condition is sufficient:

Let \( cnt( c, str ) \) denote the number of occurrences of \( c \) in some string \( str \). Then we can append \( s_i \) to \( ans \) if and only if for all \( c \), \[ cnt( c, ans ) + cnt( c, s_{ i, i + 1, \ldots, n - 1 } ) \geq cnt( c, s ) / 2 \]
The rationale for the above condition is the following. Let's examine each character that we have already added to \( ans \) (i.e. \( cnt( c, ans ) \)), as well as each character which we could potentially add to \( ans \) in the future (i.e. \( cnt( c, s_{ i, i + 1, \ldots, n - 1 } ) \) ). In order for us to produce a valid string in the end, these two numbers together must be at least equal to the number of characters we need in the final string, which is \( cnt( c, s ) / 2 \). This is both necessary and sufficient for \( s_i \) to be a valid addition to \( ans \).

Once we have the above condition, the pseudocode now looks like this:

f( s )
{
  ans = "";
  last = 0;
  for t from 0 to length(s) / 2
  {
    best = last;

    for i from last to length(s)
    {
      ok = true;
      for c from 'a'  to 'z'
        if cnt( c, ans ) + cnt( c, s.substr( i ) ) < cnt( c, s ) / 2
          ok = false;

      if ok && s[i] < s[best]
        best = i;
    }

    ans += s[best];
    last = best;
  }
}

SpellCards

We can solve this problem in a similar manner as we solved its division 2 version. All we have to do is to rotate the string, and compute the same recurrence relation as above. However, there is a more nifty solution that's trickier to see, but much, much easier to code. It turns out that SpellCards is equivalent to the knapsack problem, where each object \( i \) has weight \( lvl_i \) and value \( dmg_i \).

Proof: It suffices to show that a set of cards \( S = \{ x_1, x_2, \ldots, x_m \} \) can be played if and only if \[ \sum_{ x \in S } lvl_x \leq n \] One direction is clear -- all solutions to SpellCards must also be solutions to knapsack. For the converse, assume the above inequality holds for some set of cards \( S = \{ x_1, x_2, \ldots, x_m \} \).

Claim: There must be at least one card \( x_i \) that we can use without removing any other cards in \( S \) in the process.

Proof of claim: Assume the contrary -- that for each \( x_i \), there is some other \( x_j \) within the range \( [ x_i + 1, \ldots, x_i + lvl_{x_i} - 1 ] \) modulo \( n \). Then we have a collection of intervals \( [ x_i, x_i + 1, \ldots, x_i + lvl_{x_i} - 1 ] \) which not only cover all the cards, but also overlap. This implies that \[ \sum_{ x \in S } lvl_x > n \] which contradicts the assumption. Thus, there must be at least one card which we can use.

Given the claim, for every knapsack-satisfying set \( S = \{ x_1, \ldots, x_m \} \), we can use some \( x_i \in S \) without removing any of the other \( x_j \). This leaves us with \( n - lvl_{x_i} \) cards total. Furthermore, \[ \sum_{ x \in S \setminus \{ x_i \} } lvl_x = \left[ \sum_{ x \in S } lvl_x \right] - lvl_{x_i} \leq n - lvl_{x_i} \] I.e., after using \( x_i \), the set \( S \setminus \{ x_i \} \) still satisfies the knapsack inequality with the new set of cards. By induction, we can use all the cards if the initial set \( S \) satisfies the inequality. This completes the proof: we can solve SpellCards by simply applying a knapsack dynamic program with weights \( lvl_i \) and value \( dmg_i \).

CoinsGame

The notion of an equivalence relation is a very useful tool from basic mathematics which can help us solve this problem. Equivalence relations allow us to define relationships between arbitrary subsets of a particular set \( S \) in terms of binary relations between individual elements, in effect turning \( O( 2^{|S|} ) \) amount of data into \( O( |S|^2 ) \).

In this problem, we would like to consider the following relation: for two given non-obstacle squares in the grid \( a \) and \( b \), place coins on both \( a \) and \( b \). We say \( a \sim b \) (or \( a \) is similar to \( b \)) if every sequence of moves that causes \( a \)'s coin to fall off also causes \( b \)'s coin to fall off, and vice versa. I.e., the starting configuration consisting of coins on \( a \) and \( b \) is not a good configuration. (The proof that this is an equivalence relation is left to the reader.)

Now suppose that from the above relation, we have equivalence classes \( C_1, C_2, \ldots, C_m \) that partition \( S \), the set of non-obstacle squares. By the way we defined the relation, an initial configuration is good if and only if it contains some squares in at least two classes. Then the total number of good configurations is the number of configurations containing only squares in one class, namely \[ 2^{|S|} - 1 - \sum_{i} \left( 2^{|C_i|} - 1 \right) \]

It remains to determine how we actually compute the equivalence classes. We do this by computing which pairs \( a, b \) are not similar, i.e. there exists some sequence of moves which causes \( a \)'s coin to fall off, but not \( b \)'s, or vice versa. It turns out that we can do this with a simple breath-first search (DFS will overflow the stack). Let \( prev( s, d ) \) denote the set of all squares \( t \) such that moving in direction \( d \) from \( t \) takes you to \( s \). Then the following algorithm computes whether or not pairs of squares are distinct:

boolean distinct[N][N];

list q;
for( square s0 )
for( square s1 )
{
  distinct[s0][s1] = false;
  for( each direction d )
  {
    let s0' = move in direction d from s0;
    let s1' = move in direction d from s1;
    if( ( s0' is off the board ) ^ ( s1' is off the board ) )
      distinct[s0][s1] = true;
  }
  if( distinct[s0][s1] )
    q.add( s0, s1 )
}

while( q is not empty )
{
  s0, s1 = q.pop();
  for( each direction d )
  for( t0 in prev( s0, d ) )
  for( t1 in prev( s1, d ) )
  {
    if( !distinct[t0][t1] )
    {
      distinct[t0][t1] = true;
      q.add( t0, t1 );
    }
  }
}
This algorithm runs in \( O( |S|^2 ) \); since \( S \leq 1600 \), this will complete in under the time limit.

Once we have computed which pairs are distinct, it is quite simple to figure out the equivalence classes and then compute the final answer.

Footnotes

  1. This is a very standard technique in designing amortised algorithms: you keep track of the 'costs' you incur, and then you figure out how to 'distribute' them optimally later. Resizing ArrayLists or vectors is a classic example of a commonly used amortised algorithm.

Saturday, November 17, 2012

General Impressions about InterviewStreet

As a longtime participant of programming competitions (ACM-ICPC, TopCoder, Code Jam, Codeforces, SPOJ, etc...), I initially found the idea of InterviewStreet to be promising. Like TopCoder and other similar competitions, it builds connections between companies and a wide talent pool. However, I feel the attention that InterviewStreet receives is undeserved. While it excels at attracting industry partners to sponsor it and use its platform, the quality of the competitor-facing side of the website is very lacking.

The main problem that I have with InterviewStreet is that the website's problem statements are very rough and unpolished, often lacking crucial details and having contradictory statements or examples. While it seems like the people behind InterviewStreet are familiar with other competitions, they are rather poor producing problem statements of the same quality. The writers' seem to have a poor grasp of English, and are very bad at expressing things in an unambiguous, mathematical manner, as is required by these types of competition sites. For example, consider the following screenshot of a problem statement:

When I see this image, I immediately notice a few things:

  1. The final sentence of the first paragraph asks the reader to "find out the number of zombies at every junction after 'k' timesteps". Many problem-solvers will realise that the problem asks for the expected value of the number of zombies, but to new users or to users for whom English is not a native language, this sentence can seem very confusing.
  2. It's not specified what a zombie will do in the case where there are no neighbouring junctions.
  3. The input format doesn't specify whether the numbers are separated by spaces, newlines, commas, or arbitrary characters. Once again, one can read the example input to figure this out, but this should not be necessary. The input format should completely describe all possible input.
  4. There are lots of stylistic issues. All the input variables are uppercase, except for 'k', which is lowercase. Word choice is not the best, and the grammar and spelling are terrible. All in all, these small details make the statement much harder to parse, unlike statements on other websites like TopCoder.

This is not an isolated case -- in the InterviewStreet Collegiate Challenge last spring, there were contradictions between the problem descriptions and the input, causing participants to lose valuable coding time. (Strangely enough, the results of the collegiate challenge are no longer posted on InterviewStreet's website.) Many of the other challenges on the website suffer from the same problem. The result of having poor problem statements is like having students take a poorly-written exam in a class -- less-talented students may stumble upon correct answers, which smarter students may fail. In this case success on InterviewStreet is as much dependent on being able to decipher poorly-written English as it is on having true programming skills. I do not exaggerate when I say that some of these problems contain the worst writing that I've ever seen in competitive programming. For comparison, look at the ACM-ICPC, TopCoder, Google Code Jam, or Kaggle. Should InterviewStreet wish to remain competitive (or be taken seriously, for that matter), it should put more effort into producing higher-quality problem statements.

InterviewStreet also fails to leverage the power of the programming community. One of Codeforces' first features when the launched in 2010 was to provide a blogging framework for its participants. Likewise, TopCoder has a wiki and forum, and hosts an extensive series of community-written articles. InterviewStreet has a forum, but few people seem to use it (perhaps because of the problems above).

Despite all of this, InterviewStreet does a good job in attracting industry partners, which I would attribute mostly to hype and rhetoric about its appeal as a 'startup' with potential to 'disrupt' the talent search process. If I were a company or startup looking for talent, I would turn instead to Kaggle, TopCoder, or Codeforces -- websites which provide great platforms for similar competitions, with well-established communities and some of the most impressive talent pools in the world. In the past I have heard that InterviewStreet is better for job-searching than TopCoder, but if the current trend continues, that will no longer be the case.