Tuesday, November 27, 2012

A Morse Decoder



I couldn't resist tackling this puzzle at home, given that it is named for my distant relative, Samuel F.B. Morse.  My colleague brought it in as a potential onsite interview question for a candidate we were considering.  I can't help but be addicted by puzzles anyways, I love the challenge.



The premise is this:  You have found a stream of dots and dashes which someone has told you is a Morse Code representation of some phrase.  The problem is that Morse Code uses a timing gap to represent spaces between letters, and the spaces were ignored here.  If you were given a list of possible words, and a hash table mapping of Morse style dots and dashes to the alpha character they represent, could you recover the original phrase?



This problem really has two steps... recover possible encoding of Morse code to letters, and then breaking the letters up into possible words that could match the letters.  Both of these steps are actually the same procedure with a different mapping, so we may be able to achieve our goals with a single function reused multiple times.  Clearly the input stream could be thought of as a tree of possible mappings, and this lends itself well to a recursive approach.  Each character that has a Morse encoding that could match to the front of the stream is a potential branch.  If we assume the phrase is only complete words, we throw out any leaf where we couldn't completely find valid mappings all the way to the end of the string.  Likewise, we through out any letter mapping that doesn't finish with a valid word.

My approach is to create a class that has properties for the MorseCode characters, and the list of words making up the dictionary, so that one instance could be reused to recover phrases without having to constantly pass the same mappings.  I'm going to have a public "DecodePhrases" method that takes a string of Morse Code charactors, and returns an enumeration of possible valid solutions.  I have one private helper function which takes in some additional parameters about the node of the tree that we are currently at, and reuse this function for both encoding steps.  My code came out as follows:

    public class Decoder
    {
        public Dictionary Words { get; set; }
        public Dictionary MorseLetters { get; set; }

        public Decoder(List words, Dictionary morseLetters)
        {
            MorseLetters = morseLetters;
            Words = new Dictionary();
            words.ForEach(w => Words[w] = " " + w);
        }

        public IEnumerable DecodePhrases(String input)
        {
            return GenerateCandidates(input, "", MorseLetters)
                .SelectMany(letters => GenerateCandidates(letters, "", Words))
                .Select(phrase => new String(phrase.Skip(1).ToArray()));
        }

        private IEnumerable GenerateCandidates(String input, String candidate, Dictionary validCandidates)
        {
            if (input == "")
                return new List(){candidate};
            return Enumerable.Range(1, input.Count())
                .Select(i => new
                                 {
                                     inp = new String(input.Skip(i).ToArray()),
                                     can = new String(input.Take(i).ToArray())
                                 })
                .Where(c => validCandidates.ContainsKey(c.can))
                .SelectMany(c => GenerateCandidates(c.inp, candidate + validCandidates[c.can], validCandidates));
        }
    }

I followed it up with some NUnit tests to just make sure I wasn't full of crap...

        [Test]
        public void TestSolutionThisIsATest()
        {
            var words =
                "this is a test of the emergency broadcast system.  it is only a test."
                .Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();


            var testPhrase = String.Join("", "thisisatest".Select(c => MorseLetters.Where(p => p.Value == c.ToString()).First().Key));

            var decoder = new Decoder(words, MorseLetters);
            decoder.DecodePhrases(testPhrase);

            Assert.AreEqual("this is a test", decoder.DecodePhrases(testPhrase).First(), "properly decodes the message");
        }

And there you go! A simple function for decoding Morse Code when spaces and stops are omitted.

Tuesday, November 20, 2012

Interviewing Engineers


  This past week, I participated on the interview committee for three candidates at our company.  I've been on both sides of the interview process, both at big and small companies, and am convinced that the industry does a poor job of identifying stellar candidates.  Too many unqualified candidates are able to slip through our preliminary screens because people will fill out their resume with buzz words which they don't really understand.  Too many people slip through phone screens because the questions asked are too simple, and don't adequately separate good from the bad.  Too many good candidates are screened out by questions testing development in a way that doesn't match real programming.  Finally, too many bad candidates are simply given a pass because a binary evaluation  in a vacuum of information favors the candidate.  So what kind of steps could the industry take to insure the best candidate gets the job?
Good candidates should be found by looking for the right things


  First, where do we find our candidates?  Companies pull from a wide list of sources, some of which are more reliable than others.  Recruiting services and job fairs represent the shotgun approach, leading to the full gambit of qualified and unqualified candidates.  It is far too expensive to adequately reduce this list to candidates who would be a good fit, so they should just be eliminated.  Niche communities of programmers represent candidates who get involved in their craft at a greater depth, and could serve as a more effective source of recruiting.  Job boards on developer sites like StackOverflow, or from communities like TopCoder have a built in bread crumb trail to help validate a candidate before ever even looking at their resume.  Good candidates stick out, and that should be your first screen.  Another primary source of candidates should be your dev evangelists.  Engineers who attend tech talks outside of working hours have demonstrated a level of commitment beyond the average developer.  And if they are going to a talk about your own product, they probably already like you, and are ahead on the learning curve.

Good candidates should be able to make good designs


  Second, what questions should we ask them during a screen?  I agree with Jeff Atwood on this point; the phone screen should weed out candidates with gaping holes in their knowledge.  There are just some broad areas of knowledge that all good software engineers know something about.  First, algorithms.  I'm not talking about remembering the details of an algorithm taught in a classroom, but the on the fly problems like reversing the order of all words in a string.  Candidates should be able to analyze the efficiency of their algorithms, and a good candidate with a  handle on different types of data structures will know the trade-offs    that lead to more optimal solutions.  Next, candidates need to show they know how to design systems.  Ideally, a candidate has a grasp of common design patterns, so if you give them a problem that just screams for a solution, good candidates will lean on that past experience.  Candidates without explicit experience with design patterns still can preform well, since design patterns just give a language to ideas that all engineers should be familiar with anyways.  Third, scripting and regular expressions.  Parsing data turns out to be an important part of so many tasks, so a good candidate will have these tools in their belt.  Fourth, bits and bytes.  If you ask a candidate to find the number of bits set to 1 in an integer, they should be able to whip through a solution that picks them out.  If you have a candidate who does well with these questions, it will go a long way to assuring that your candidate is qualified.



  Next comes the onsite interview.  I'd have three goals of things to learn about the candidate at this stage.  First, does the candidate have any specialized knowledge relevant to the position you are hiring for?  For this, you should get an interviewer who knows the technology stack in question, and can answer.  Second, can a programmer work through a more complicated problem, something that is going to take a significant amount of time?   Third, are they a good culture fit with your company?  The biggest issue I have with current industry practices is that most developers are asked to solve problems at the whiteboard, which in my opinion bares little resemblance to how a developer actually writes code.  I would ask a candidate to bring in their laptop, and solve the problem using any environment they want to use, and any online resources they need.  The problem asked can't be easy to solve, so I might pick a question similar to those used in a TopCoder SRM, or in a round of Google Code Jam, which are intended to be solved in about a half hour.

Good candidates should not be evaluated in a vacuum, but against other candidates

  Finally, comes the hire/no hire decision being asked of the interviewer.  In most instances, they aren't given any metrics against which to compare for evaluating a candidate, other than their own gut feelings.  And software engineers have a track record about getting things wrong when they go with their gut.  That is a big motivation why the Agile process was developed, as a way of giving engineers mechanisms for estimating complexity of code by comparing against the complexity of past stories.  I think similar lessons could be applied to the interview process.  If interviewers were instead asked to rank candidates they had seen before, or assign planning poker numbers to the candidates, we would gain a better understanding of how an interview experience went.  Due diligence means each interviewer should be interviewing a wide range of candidates before a final hire no-hire decision is made for a position.  It may be a timely and expensive process, but I assure you hiring the wrong candidate is much more so.

  While there may not be a foolproof way to identify good teammates, there are many steps that can be taken to make the process more efficient.  Limiting your sources to places where more good candidates live, vetting candidates based on their online bread crumb trail, asking relevant questions that test their skills in a way that compares well to how real development is done, and evaluating candidates against other candidates are just a few ideas I have about how we can approach those goals.  Better developers means better teams means better products.  This is all something we should strive to provide.

Saturday, November 17, 2012

ACM Queue ICPC Challenge


Every year, ACM puts on a month long programming contest challenging developers to pit their wits against one another in some unique type of battle royal.  Typically, the competition takes place on some kind of loosely physically based game board, where each person controls a team of agents who must cooperate in achieving some sort of collective goal, while thwarting the efforts of their opponents.  It tests many elements of a software engineer.  How well can you break down a complex problem?  How good are you at balancing tactics and strategy?  How do you coordinate your efforts?  Its an AI geeks dream.


The competition has traditionally been built off the previous ICPC collegiate challenge... so we can get a sneak peek at this years challenge here.  This year, we get to control a fleet of bumper boats, carrying a baton between way-points forming a course.  Complete the circuit more times than your opponent completes theirs, and you win.

Here is a video of some of the competition at the collegiate challenge.  There are just so many good ideas for strategies, I can hardly wait to start developing my own AI.  I'll post updates about my engine as I get going. Looking forward to another good year of competition!

Thursday, November 15, 2012

My Technical Blog

One of the core qualities of a professional software developer is to constantly strive for self improvement.  That can mean many things, from being active in local user groups, to reading technical books, to learning a new programming language every year, to starting your own blog.  I've been blessed with a few mentors that I can look to as professional role models.  These are people who take their craft very seriously, and the industry benefits from their experience.  For them, it is always about radically stretching themselves to find new and better ways to build systems and develop software, always on the leading edge.  And for them, it also means giving back to the generous community that helped support them in becoming the professionals they are today.  Well, now its my turn to take a crack at it.  I hope to use this blog both as a tool for myself to explore different aspects of being on the bleeding edge of technology, and as a guidepost to others who may still be early on in their careers, to help them learn from my mistakes, and encourage them to become guides to others.