Earlier today I ran across a job posting that had a small test, I wasn't interested in the job but I liked the test. One problem was to write a date sorter without using a date parsing library. The format to be parsed is: "Sep 1 2010". Normally I would write something like this in a few lines of Python or Perl, but I decided to tackle the problem in C, just to make it harder. Since regular expressions were allowed, I thought it was okay to use sscanf.
One of the first thing's you'll see is that I took a page from Perl's spaceship operator, and defined a macro that will compare two numbers and return -1 if it is less, 0 if equal and 1 if greater. Normally for a sorting algorithm you would only need to know if it is less or not, but I wanted to chain comparisons together by falling down to the next comparison when two values are equal.
Another trick I used is a bit of a hack to find the the number corresponding to the month. You'll notice that I cast char *a to uint32_t as a way to avoid strcmp. I'm not sure if I would do this in production code, but its a fun trick.
Full code is below.
No comments:
Post a Comment