Codehire Cup Solutions: Grand Final

A solution in Ruby to the Grand Final problem in the inaugural Codehire Cup held in September 2012 at the University of Adelaide.

In September 2012, Codehire held the inaugural Codehire Cup in Adelaide, featuring some relatively simple coding problems. Contestants could choose to use C#, Java, JavaScript, PHP, or Ruby to submit solutions through a web-based interface. Fastest contestant wins.

The Problem

The Grand Final problem read:

John meets a girl in a bar. He doesn’t know her but she’s knows him. She says that they have exactly 1 single facebook friend in common.

Write a program to help John narrow down the search for this girl. You have access to a friends graph in your input string.

You need to find all of the users that have exactly 1 friend in common with John.

Each friend is represented by a number with John’s number being 1. A connection (or friendship) is represented by two user numbers separated by a hyphen:

For example, users 1 and 2 are friends:


Use the input to find all users that have exactly 1 friend in common with John.

For example:


Should return the list of matching users in ascending order.


The Solution

The solution to this problem involves two simple steps. First, we parse the input string to get an array for each person containing that person’s friends. Then, we can compute the intersections of the array of John’s friends and each of the other arrays of friends using the built-in Ruby & operator, and select the people where the size of that intersection is 1.

map =[])
input.scan /(\d+)-(\d+)/ do |a, b|
    map[a] += [b]
    map[b] += [a]

john = map.delete('1')! { |k, v| (v & john).size == 1 }
output << map.keys.sort.join(',')

More Codehire Cup Solutions

Tags: Codehire Cup, coding contests