Tips for the Google Code Jam Programming Contest

This year I decided to compete in Google Code Jam. I thought it would challenge my knowledge of algorithms and complexity classes, or my ability to write code cleanly or quickly leveraging the IDE. Nope, not even close. I quickly learned the so-called coding competition is really a problem-reading competition. Here are the top lessons I took away:
  1. Pay attention to detail. Often times, I would think I understood the problem and only after coming up with a failing solution would I realize I skimmed over one sentence that changes the nature of the solution entirely. Do not give in to pressure and skim over lines. The contest tests your ability to understand a word problem completely and solve it with an algorithm, not how fast you can code.
  2. You don’t need fancy languages, libraries, or IDEs. I made the mistake of trying to solve a constraint-based problem in Prolog which I hadn’t touched for 3 years and ended up wasting half an hour. You do not need objects, lambdas, or magical libraries. All you need are ints, doubles, and if-thens and for-loops.
  3. You don’t get points for cleanliness. Unlike a real project where things like well-named variables and refactored functions matter, all the top contests use single-letter variables and their code reads like spaghetti. 
  4. Use a template for reading and writing the files. All the input and output files are in a standard format you should just copy and paste between problems. I wasted several minutes during the first round trying to get my input and output correct.
  5. Practice, practice, practice. I took the Code Jam for fun this year so I didn’t prepare and was happy to place 2,000 out of 17,000. But I realized if a lot of this boils down to practice. And practicing problems will make you a better programmer. Next year I plan on making it to Round 3 and hopefully the finals. I’m coming for you Code-Jam T-Shirt! 

How to drop files from explorer into Java

All you need to do is call setDropTarget() on the component you need to drop onto, passing in a delegate object (in this case I created one called FileDropTarget) that handles the drop operation.

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.*;
import java.io.File;
import java.util.List;

import javax.swing.JFrame;

public class Demo {
 public static void main(String[] args) {
  JFrame frame = new JFrame();
  frame.setDropTarget(new FileDropTarget());
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
 }

 private static class FileDropTarget extends DropTarget {
  private static final long serialVersionUID = 1L;

  @Override
  @SuppressWarnings("unchecked")
  public synchronized void drop(DropTargetDropEvent event) {
   try {
    event.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
    Transferable transferable = event.getTransferable();
    Object data = transferable.getTransferData(DataFlavor.javaFileListFlavor);
    List<File> list = (List<File>) data;
    System.out.println(list.get(0).getAbsolutePath());
   } catch (Exception e) {
    // Non-file dropped
   }
  }
 }
}

Inlining Mocks in Mockito

Mockito normally throws an exception when you try to inline a mock as follows:
Zoo zoo = mock(Zoo.class);
when(zoo.getAnimal()).thenReturn(mock(Animal.class));

One work-around is to do the following:
Zoo zoo = mock(Zoo.class);
Animal animal = mock(Animal.class);
when(zoo.getAnimal()).thenReturn(animal);

However, the test code is annoyingly verbose if we need more complex mocking:
Zoo zoo = mock(Zoo.class);

Animal tiger = mock(Animal.class);
Animal monkey = mock(Animal.class);
Animal zebra = mock(Animal.class);

when(tiger.getName()).thenReturn("Tiger");
when(monkey.getName()).thenReturn("Monkey");
when(zebra.getName()).thenReturn("Zebra");

when(zoo.getTiger()).thenReturn(tiger);
when(zoo.getMonkey()).thenReturn(monkey);
when(zoo.getZebra()).thenReturn(zebra);

If only the unfinished stub verification didn't throw errors during inline mocking, we could refactor the test code into something like this:
MockInliner.install();
Zoo zoo = mock(Zoo.class);
when(zoo.getTiger()).thenReturn(mockAnimal("Tiger"));
when(zoo.getMonkey()).thenReturn(mockAnimal("Monkey"));
when(zoo.getZebra()).thenReturn(mockAnimal("Zebra"));

So I wrote a class to get around it. Copy and paste the following class into your project:
package ripper;

import java.lang.reflect.Field;

import org.mockito.Mockito;
import org.mockito.exceptions.misusing.UnfinishedStubbingException;
import org.mockito.internal.MockitoCore;
import org.mockito.internal.progress.*;

@SuppressWarnings("unchecked")
public class MockInliner {
 public MockInliner() {
  install();
 }

 public static void install() {
  trySetMockingProgressImplementation(new InlineMockingProcess());
 }

 public static void uninstall() {
  trySetMockingProgressImplementation(new MockingProgressImpl());
 }

 private static void trySetMockingProgressImplementation(MockingProgress progress) {
  try {
   setMockingProcessImplementation(progress);
  } catch (Exception e) {
   throw new RuntimeException("Unable to set mocking progress, Mockito implementation must have changed", e);
  }
 }

 private static void setMockingProcessImplementation(MockingProgress progress) throws Exception {
  Object core = getHiddenField(Mockito.class, null, "MOCKITO_CORE");
  Object mocking = getHiddenField(MockitoCore.class, core, "mockingProgress");
  Object implementation = getHiddenField(ThreadSafeMockingProgress.class, mocking, "mockingProgress");
  ((ThreadLocal<MockingProgress>) implementation).set(progress);
 }

 private static Object getHiddenField(Class<?> clazz, Object obj, String name) throws Exception {
  for (Field field : clazz.getDeclaredFields())
   if (field.getName().equals(name)) {
    field.setAccessible(true);
    return field.get(obj);
   }
  throw new NoSuchFieldException("Field " + name + " not found");
 }

 private static class InlineMockingProcess extends MockingProgressImpl {
  @Override
  public void validateState() {
   try {
    super.validateState();
   } catch (UnfinishedStubbingException e) {
    // Do not fail
   }
  }
 }
}

Full disclosure, the code is just a hack to suppress the exception, tied to the implementation of Mockito through reflection. Once installed, Mockito won't check for unfinished stubs. Anyway here is the test code for those interested:
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.mockito.exceptions.misusing.UnfinishedStubbingException;

public class MockInlinerTest {

 @Test(expected = UnfinishedStubbingException.class)
 public void cannotNormallyInlineMocks() throws Exception {
  Zoo zoo = mock(Zoo.class);
  when(zoo.getTiger()).thenReturn(mock(Animal.class));
 }

 @Test
 public void canInlineMocksWithInlinerInstalled() throws Exception {
  MockInliner.install();
  Zoo zoo = mock(Zoo.class);

  when(zoo.getTiger()).thenReturn(mockAnimal("Tiger"));
  when(zoo.getMonkey()).thenReturn(mockAnimal("Monkey"));
  when(zoo.getZebra()).thenReturn(mockAnimal("Zebra"));

  assertThat(zoo.getMonkey().getName(), equalTo("Monkey"));
 }

 private Animal mockAnimal(String name) {
  Animal animal = mock(Animal.class);
  when(animal.getName()).thenReturn(name);
  return animal;
 }

 private interface Zoo {
  Animal getZebra();

  Animal getMonkey();

  Animal getTiger();
 }

 private interface Animal {
  String getName();
 }
}