Solving the Hyperpublic Coding Challenge in Mathematica

I quite enjoy the various coding challenges that appear to be gaining in popularity. Greplin's was a lot of fun and yesterday Hyperpublic released one of their own. Since I just noticed that a number of people have posted their answers I thought I'd post mine.

I like to use Mathematica for these challenges. Why? It's a really powerful environment, it's a lot of fun to use, I have a copy :-), and completing these challenges always teaches me more about Mathematica itself.

Challenge 1

In this test you're given a file that represents which users have invited others, defines an influence metric, and asks you to find the influences of the top three influencers.

Read in the sample file
l = ReadList[NotebookDirectory[] <> "Hyperpublic Q1.txt", String];

Define a function that returns the positions of the Xs in a line
CalcFriends[s] := Map[(#[[1]] &), StringPosition[s, "X"]]
This returns a list of the positions of the Xs in a String
E.g. CalcFriends of the fifteenth line (which represents a user with four friends) generates the indices of those friends
{12, 23, 84, 93}
A line with all Os (no friends for this user) gives
{ }

Map CalcFriends over the list of lines
f = CalcFriends[#] & /@ l

A recursive function to calculate a user's influence
Influence[l_List] := Length[l] + Fold[Plus, 0, Influence[f[[#]]] & /@ l]

Now we just map Influence over the output of CalcFriends and take the top 3

Take[Reverse[Sort[Influence[#] & /@ f]], 3]

Challenge 2

Here we're (essentially) asked to find the minimum of moves to achieve a target.

For some reason, even though I knew this was a linear optimization problem, I started coding it. A mistake caused me to rethink my approach which, when you're using Mathematica, usually goes along the lines of "Why am I writing code?! I'm sure there's a function for this in here somewhere!" :-)

Lo and behold, there was:
FindMinimum[ {p1 + p2 + p3 + p4 + p5 + p6, 
2 p1 + 3 p2 + 17 p3 + 23 p4 + 42 p5 + 98 p6 == 2349 && 
p1 >= 0 && p2 >= 0 && p3 >= 0 && p4 >= 0 && p5 >= 0 && p6 >= 0 && 
p6 ∈ Integers && p5 ∈ Integers && p4 ∈ Integers && p3 ∈ Integers && p2 ∈ Integers }, 
{p1, p2, p3, p4, p5, p6}]

But you should see Yaroslav Bulatov's solution for this problem, it's much more elegant.

Fun stuff... Not only does Mathematica give you some great tools for solving problems, it also solves them fast.